众所周知,Python提供的用于处理日期和时间的标准模块名为datetime.
记录当前时间戳的常用方法为
>>> import datetime
>>> datetime.datetime.utcnow()
datetime.datetime(2018, 4, 17, 8, 4, 14, 924480)
>>> datetime.datetime.now()
datetime.datetime(2018, 4, 17, 16, 4, 46, 821245)
可以看出两种方法得到的时间戳是不一样的,那么两者有什么不同呢?
python手册中是这样写的:
classmethod datetime.now(tz=None)
Return the current local date and time. If optional argument tz is None or not specified, this is like today(), but, if possible, supplies more precision than can be gotten from going through a time.time() timestamp (for example, this may be possible on platforms supplying the C gettimeofday() function).
If tz is not None, it must be an instance of a tzinfo subclass, and the current date and time are converted to tz’s time zone. In this case the result is equivalent to tz.fromutc(datetime.utcnow().replace(tzinfo=tz)). See also today(), utcnow().classmethod datetime.utcnow()
Return the current UTC date and time, with tzinfo None. This is like now(), but returns the current UTC date and time, as a naive datetime object. An aware current UTC datetime can be obtained by calling datetime.now(timezone.utc). See also now().
翻译过来就是now()返回的是当前时区的时间,这个时间就是你电脑的右下角显示时间(只要你没有调过时区)。而utcnow()返回的是世界标准时间(UTC),这个时间不分时区。
了解到这些我们也就能够满足基本需求了。接下来的是进阶需求。
当我们的业务拓展至全球,now()返回的是当地时间,这个时间与时区相关,但是却不返回时区。而utcnow()返回的是世界时间,这个时间与时区无关。它们之间的换算为:
世界时间=当地时间+(或者-)时区
当我们接收到某个时区发送过来的时间时,我们并不知道它是哪个时区的所以我们需要能够返回包含时区信息的时间戳。我们可以用ISO8601库。
测试代码如下:
>>> import datetime
>>> import iso8601
>>> import pytz
>>> def utcnow():
... return datetime.datetime.now(tz=pytz.utc)
...
>>> utcnow()
datetime.datetime(2018, 4, 17, 8, 7, 41, 300399, tzinfo=)
>>> iso8601.parse_date(utcnow().isoformat())
datetime.datetime(2018, 4, 17, 8, 10, 32, 70631, tzinfo=datetime.timezone(datetime.timedelta(0), '+00:00'))
这时就可以比较来自不同时区的时间戳了。
参考资料:《Python高手之路》(《The Hacker’s Guide to Python》第三版)第四章–时区陷阱