ZhangZhihui's Blog  

>>> from datetime import date
>>> from datetime import datetime
>>> import pytz
>>> import tzlocal


>>> loc_tz = tzlocal.get_localzone()
>>> loc_tz
<DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD>
>>> utc_tz = pytz.timezone('UTC')
>>> utc_tz
<UTC>


>>> dt1 = datetime.now()
>>> dt1
datetime.datetime(2020, 5, 2, 14, 51, 2, 160647)
>>> dt2 = datetime.utcnow()
>>> dt2
datetime.datetime(2020, 5, 2, 6, 51, 10, 338481)
>>> aware_dt1 = loc_tz.localize(dt1)
>>> aware_dt1
datetime.datetime(2020, 5, 2, 14, 51, 2, 160647, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)
>>> aware_dt2 = utc_tz.localize(dt2)
>>> aware_dt2
datetime.datetime(2020, 5, 2, 6, 51, 10, 338481, tzinfo=<UTC>)


>>> d = date(2020, 3, 1)
>>> d
datetime.date(2020, 3, 1)
>>> loc_tz.localize(d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/zzh/.pyenv/versions/3.8.2/lib/python3.8/site-packages/pytz/tzinfo.py", line 317, in localize
    if dt.tzinfo is not None:
AttributeError: 'datetime.date' object has no attribute 'tzinfo'
>>> d.tzinfo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'datetime.date' object has no attribute 'tzinfo'
>>> dt1.tzinfo
>>> dt2.tzinfo
>>>

总结:date类型没有tzinfo属性;datetime有tzinfo属性,但默认为None。

posted on 2020-05-02 15:05  ZhangZhihuiAAA  阅读(909)  评论(0编辑  收藏  举报