Python - simplest and most coherent way to get timezone-aware current time in UTC?
1 2 3 4 | >>> from datetime import datetime >>> y = datetime.now() >>> y datetime.datetime(2014, 3, 11, 11, 18, 33, 598489) |
起初我认为
1 2 3 4 | >>> from datetime import datetime >>> y = datetime.utcnow() >>> y datetime.datetime(2014, 3, 11, 16, 19, 40, 238810) |
在Python 3中:
1 | datetime.now(timezone.utc) |
在Python 2.x中没有时区对象,但您可以编写自己的对象:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | try: from datetime import timezone except ImportError: from datetime import tzinfo, timedelta class timezone(tzinfo): def __init__(self, utcoffset, name=None): self._utcoffset = utcoffset self._name = name def utcoffset(self, dt): return self._utcoffset def tzname(self, dt): return self._name def dst(self, dt): return timedelta(0) timezone.utc = timezone(timedelta(0), 'UTC') |
然后就像在Python 3中一样,你可以做
我用pytz
然后使用以下代码
1 2 3 | import pytz from datetime import datetime now = datetime.utcnow().replace(tzinfo = pytz.utc) |
使用
根据这个答案,这里是如何使对象时区感知。
1 2 3 4 | >>> import pytz >>> from datetime import datetime >>> datetime.now(pytz.utc) datetime.datetime(2014, 3, 11, 15, 34, 52, 229959, tzinfo=<UTC>) |