3.7 KiB
| title | date | tags | categories |
|---|---|---|---|
| Python模块timezone学习笔记 | 2018-08-06 18:19:30 | [python] | python |
本文基于python3,记录了datetime包中的timezone用法。
使用第三方扩展包pytz,构造指定时区。
astimezone
datetime.datetime.astimezone是将原始输入解释为本地时区,然后再转换为目标时区,而pytz包的localize方法,是将原始输入直接解释为目标时区,例如:
tz = pytz.timezone('Asia/Shanghai')
target_dt = datetime.datetime(2018, 8, 5, 0, 0, 0, 0)
print(repr(target_dt.astimezone(tz)))
print(repr(tz.localize(target_dt)))
# Output
# > datetime.datetime(2018, 8, 5, 8, 0, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)
# > datetime.datetime(2018, 8, 5, 0, 0, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)
timetuple
由于datetime.datetime.timetuple方法不存储时区,所以如果需要构造不同时区的timestamp,需要使用datetime.datetime.utctimetuple方法。
target_dt = datetime.datetime(2018, 8, 5, 0, 0, 0, 0)
print(repr(target_dt.utctimetuple()))
print(repr(target_dt.timetuple()))
# Output
# > time.struct_time(tm_year=2018, tm_mon=8, tm_mday=5, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=217, tm_isdst=0)
# > time.struct_time(tm_year=2018, tm_mon=8, tm_mday=5, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=217, tm_isdst=-1)
datetime.``timetuple()¶Return a
time.struct_timesuch as returned bytime.localtime().d.timetuple()is equivalent totime.struct_time((d.year, d.month, d.day, d.hour, d.minute, d.second, d.weekday(), yday, dst)), whereyday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1is the day number within the current year starting with1for January 1st. Thetm_isdstflag of the result is set according to thedst()method:tzinfoisNoneordst()returnsNone,tm_isdstis set to-1; else ifdst()returns a non-zero value,tm_isdstis set to1; elsetm_isdstis set to0.
datetime.``utctimetuple()¶If
datetimeinstance d is naive, this is the same asd.timetuple()except thattm_isdstis forced to 0 regardless of whatd.dst()returns. DST is never in effect for a UTC time.If d is aware, d is normalized to UTC time, by subtracting
d.utcoffset(), and atime.struct_timefor the normalized time is returned.tm_isdstis forced to 0. Note that anOverflowErrormay be raised if d.year wasMINYEARorMAXYEARand UTC adjustment spills over a year boundary.
目标需求,将东8区(+8)的2018-08-05 00:00:00转换为unix timestamp:
tz = pytz.timezone('Asia/Shanghai')
target_dt = datetime.datetime(2018, 8, 5, 0, 0, 0, 0)
target_dt = tz.localize(target_dt)
print(time.mktime(target_dt.utctimetuple()))
print(target_dt.timestamp())
# Output
# > 1533398400.0
# > 1533398400.0
参考文档:
https://kkc.github.io/2015/07/08/dealing-with-datetime-and-timezone-in-python/