3

I am new Python. I am stuck at one point. I have variable that store time as string with specified timezone.

It is look like as given below

>>> print usertime
2017-08-18T08:00:00+04:30
>>> type(usertime)
<type 'str'>

So I just want to convert usertime time to utc time, The output should subtract 4 hours and 30 minutes from 2017-08-18T08:00:00. The output conversion will look like: 2017-08-18T03:30:00 as per utc format.

2 Answers 2

3

You want to convert the string to a datetime like object first. The problem with your string is that the timezone is in a format that datetime doesn't recognise.

You could use pandas Timestamp

import pandas as pd

ts = pd.Timestamp(string).tz_convert("UTC")
output = ts.strftime("%Y-%m-%dT%H:%M:%S")

Alternatively, if you don't want to install/use Pandas, could convert the string format, and then use datetime.

import datetime
import pytz
import re

# Remove the ':' from the timezone, if it's there.
string = re.sub("\+(?P<hour>\d{2}):(?P<minute>\d{2})$", "+\g<hour>\g<minute>" , string)
# Create the datetime object.
dt = datetime.datetime.strptime(string, "%Y-%m-%dT%H:%M:%S%z")
# Convert to UTC
dt = dt.astimezone(pytz.UTC)
output = dt.strftime("%Y-%m-%dT%H:%M:%S")

If you're using python 2.7, and can't specify %z when calling strptime the standard workaround is to do this:

def parse(string):
    dt = datetime.strptime(string[0:19],'%Y-%m-%dT%H:%M:%S')
    if string[19] == "+":
        dt -= datetime.timedelta(hours=int(string[20:22]), 
                                 minutes=int(string[22:]))
    elif t[19]=='-':
        dt += datetime.timedelta(hours=int(string[20:22]),
                                 minutes=int(string[22:]))
    return dt

The advantage of the methods above, vs Stefano's answer, is that they will work with an arbitrary offset. Not just for four and half hours.

Sign up to request clarification or add additional context in comments.

1 Comment

Within Python 2.7 dt = datetime.datetime.strptime(string, "%Y-%m-%dT%H:%M:%S%z") will throw a ValueError: 'z' is a bad directive in format '%Y-%m-%dT%H:%M:%S%z'
-1

You can install the package python-dateutil with pip and use "parser" to convert your string into datetime format (utc) and you can use timedelta to subtract the 4 hours and 30 minutes.

from datetime import datetime, timedelta
from dateutil import parser
usertime = "2017-08-18T08:00:00+04:30"
date = parser.parse(usertime)
date = date - timedelta(hours=4, minutes=30)
print date
2017-08-18 03:30:00+04:30

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.