问题
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.
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/45650853/how-to-convert-string-with-timezone-to-datetime-in-utc-with-python