Python学习之datetime时间戳

众所周知,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=<UTC>)
>>> 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》第三版)第四章–时区陷阱

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值