3 回答
TA贡献1818条经验 获得超8个赞
tzinfo
tzinfo
from datetime import datetime
from dateutil import tz
# METHOD 1: Hardcode zones:
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('America/New_York')
# METHOD 2: Auto-detect zones:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
# utc = datetime.utcnow()
utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')
# Tell the datetime object that it's in UTC time zone since
# datetime objects are 'naive' by default
utc = utc.replace(tzinfo=from_zone)
# Convert time zone
central = utc.astimezone(to_zone)
编辑扩展示例显示strptime使用
编辑2修正API使用以显示更好的入口点方法
编辑3包括时区自动检测方法(亚林)
TA贡献1828条经验 获得超6个赞
from datetime import datetimeimport timedef datetime_from_utc_to_local(utc_datetime): now_timestamp = time.time() offset = datetime.fromtimestamp(now_timestamp) - datetime.utcfromtimestamp(now_timestamp) return utc_datetime + offset
offset = datetime.fromtimestamp(0) - datetime.utcfromtimestamp(0) # NO!
最新情况:
def utc2local (utc): epoch = time.mktime(utc.timetuple()) offset = datetime.fromtimestamp (epoch) - datetime.utcfromtimestamp (epoch) return utc + offset
添加回答
举报