[英]How to convert datetime string without timezone to another datetime with timezone in python?
I can't seem to figure out how to convert a datetime string to another datetime string with timezone. 我似乎无法弄清楚如何将一个datetime字符串转换为带有时区的另一个datetime字符串。
Here's the example. 这是例子。
07/27/2015:06:00 AM
to 20150727060000 -0400
20150727060000 -0400
07/27/2015:06:00 AM
至20150727060000 -0400
The default timezone would be EST. 默认时区为EST。
Here's my code so far. 到目前为止,这是我的代码。
from datetime import datetime, timedelta
def _to_datetime(air_date, air_time):
schedule_time = '{}:{}'.format(air_date, air_time)
return datetime.strptime(schedule_time,'%m/%d/%Y:%I:%M %p')
Use pytz
module to work with timezones in Python. 使用
pytz
模块在Python中使用时区。 To get the local timezone as pytz
tzinfo object, you could use tzlocal
module: 要将本地时区作为
pytz
tzinfo对象,可以使用tzlocal
模块:
from tzlocal import get_localzone # $ pip install tzlocal
naive = _to_datetime('07/27/2015', '06:00 AM')
aware = get_localzone().localize(naive, is_dst=None)
print(aware.strftime('%Y%m%d%H%M%S %z'))
# -> 20150727060000 -0400
Add the time zone to the parsed string with %z
. 使用
%z
将时区添加到已解析的字符串中。 This will give it a tzinfo
attribute: 这将为其赋予
tzinfo
属性:
from datetime import datetime, timedelta
def _to_datetime(air_date, air_time):
schedule_time = '{}:{}'.format(air_date, air_time)
return datetime.strptime(schedule_time + ' -0400', '%m/%d/%Y:%I:%M %p %z')
Example: 例:
>>> datetime.strptime('03/19/2015:03:00 PM -0400','%m/%d/%Y:%I:%M %p %z')
datetime.datetime(2015, 3, 19, 15, 0, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000)))
You could use dateutil
to add the tzinfo
to the datetime
object. 您可以使用
dateutil
将tzinfo
添加到datetime
对象。
from datetime import datetime, timedelta
from dateutil import tz
AmericaNewYorkTz = tz.gettz('America/New_York')
def _to_datetime(air_date, air_time):
schedule_time = '{}:{}'.format(air_date, air_time)
return datetime.strptime(schedule_time,'%m/%d/%Y:%I:%M %p').replace(tzinfo=AmericaNewYorkTz)
dt = _to_datetime('07/27/2015', '06:00 AM')
print('DateTime:', dt)
# DateTime: 2015-07-27 06:00:00-04:00
or as JH Sebastian pointed out, you can use pytz
或正如JH Sebastian所指出的,您可以使用
pytz
from datetime import datetime, timedelta
from pytz import timezone
AmericaNewYorkTz = timezone('America/New_York')
def _to_datetime(air_date, air_time):
schedule_time = '{}:{}'.format(air_date, air_time)
naiveDateTime = datetime.strptime(schedule_time,'%m/%d/%Y:%I:%M %p')
localizedDateTime = AmericaNewYorkTz.localize(naiveDateTime, is_dst=None)
return localizedDateTime
dt = _to_datetime('05/27/2015', '06:00 AM')
print('DateTime:', dt)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.