Python模块timezone学习笔记

本文基于python3,记录了datetime包中的timezone用法。

使用第三方扩展包pytz,构造指定时区。

astimezone

datetime.datetime.astimezone是将原始输入解释为本地时区,然后再转换为目标时区,而pytz包的localize方法,是将原始输入直接解释为目标时区,例如:

1
2
3
4
5
6
7
8
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方法。

1
2
3
4
5
6
7
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_time such as returned by time.localtime(). d.timetuple() is equivalent to time.struct_time((d.year, d.month, d.day, d.hour, d.minute, d.second, d.weekday(), yday, dst)), where yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1 is the day number within the current year starting with 1 for January 1st. The tm_isdst flag of the result is set according to the dst() method: tzinfo is None or dst() returns None, tm_isdst is set to -1; else if dst() returns a non-zero value, tm_isdstis set to 1; else tm_isdst is set to 0.

datetime.``utctimetuple()

If datetime instance d is naive, this is the same as d.timetuple() except that tm_isdst is forced to 0 regardless of what d.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 a time.struct_time for the normalized time is returned. tm_isdst is forced to 0. Note that an OverflowError may be raised if d.year wasMINYEAR or MAXYEAR and UTC adjustment spills over a year boundary.

目标需求,将东8区(+8)的2018-08-05 00:00:00转换为unix timestamp:

1
2
3
4
5
6
7
8
9
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/

发布时间: 2018年08月06日 - 18时19分
更新时间: 2018年10月17日 - 21时42分
原始链接: https://oaoa.me/posts/a56ea470/