http://www.dannysite.com/blog/122/
The datetime module in the Python standard library provides a variety of methods for handling dates and times. Starting with the topic in this article, first take advantage of the UtcNow () method provided in DateTime to get to the current UTC time:
| 1234 |
>>> import datetime >>> utc_now = datetime.datetime.utcnow () >>> utc_now datetime.datetime ( 2013 , 12 , 4 , 15 , 43 , 21 , 872000 ) |
And at this point its tzinfo is none:
When the international time zone is involved, the time zone conversion is often used, for example, to try to convert the UTC time to local time. For the python3.3+ version, you can do this:
| 12 |
>>> utc_now.replace(tzinfo=datetime.timezone.utc).astimezone(tz=None)datetime.datetime(2013, 12, 4, 23, 43, 21, 872000, tzinfo=datetime.timezone(datetime.timedelta(0, 28800), ‘中国标准时间‘)) |
However, this method seems inconvenient, especially when converting other time zones. For the lower version of Python, Datetime.timezone may not have yet. Therefore, a more convenient way is to implement--PYZT with a third-party package, which is used to implement the time zone transformation:
| 12345678 |
>>> frompytz importtimezone>>> utc_now.tzinfo>>> tzchina =timezone(‘Asia/Chongqing‘)>>> tzchina<DstTzInfo ‘Asia/Chongqing‘LMT+7:06:00STD>>>> utc =timezone(‘UTC‘)>>> utc_now.replace(tzinfo=utc).astimezone(tzchina)datetime.datetime(2013, 12, 4, 23, 43, 21, 872000, tzinfo=<DstTzInfo ‘Asia/Chongqing‘CST+8:00:00STD>) |
To convert to a different time zone, and so on.
For me, time zone conversions are mostly in Django, and it's often necessary to convert UTC time to local time, and Django itself has taken this into account, so it's easier to actually do it:
| 12345 |
>>> from django.utils.timezone importutc>>> fromdjango.utils.timezone importlocaltime>>> now =datetime.datetime.utcnow().replace(tzinfo=utc)>>> localtime(now)datetime.datetime(2013, 12, 5, 0, 3, 13, 122000, tzinfo=<DstTzInfo ‘Asia/Shanghai‘ CST+8:00:00STD>) |
There are many ways to convert the time zone in Python, and it may be possible to find a better way to do so.
DateTime Time Zone Conversion