with the increasing demand for internationalization, it is inevitable that multiple time zones are involved while considering multiple languages.
the multi-language i18n support in python is much better, but it is slightly worse in processing multiple time zones, although the python Standard Library provides tzinfo In datetime, it is a pity that it is only an abstract class and you need to implement tzinfo by yourself. To implement local timezone, you can use the time of the time module. timezone . The strange thing is, why not provide a local timezone In the python standard library? What is even more confusing is that the strptime method of datetime in Python does not support parsing time strings with time zones. In the current situation, if you want to Code independently or independently, only hope for python 3. x, at least the solution is not found in the standard library of python2.7.2.
currently, to properly solve the problem of multiple time zones in Python, we recommend using Python-dateutil and pytz, however, parser in Python-dateutil is short for pytz and can be used to parse time strings.
The following is a simple code example to show how to use Python-dateutil to parse strings with time zones and how to use datetime to output time strings with Time Zone IDs:
#-*-Encoding: UTF-8-*-import datetimeimport timeimport dateutilfrom dateutil. parser import parsedef test_format (): Print "test time format with timezone" FMt = '% Y-% m-% d % H: % m: % S % Z' now = datetime. datetime. now () print now. strftime (FMT) Now = datetime. datetime. now (dateutil. tz. tzlocal () now_str = now. strftime (FMT) print "now is:" Print now_str print "utcnow is:" Print datetime. datetime. utcnow () datestr = "14:00:01 + 07" DT = parse (datestr) print "original datetime", DT. strftime (FMT) print "Local datetime", DT. astimezone (dateutil. tz. tzlocal ())
The above code runs as follows:
>>>
Test time format with timezone
2011-12-01 19:15:27
Now is:
19:15:27 + 0800
Utcnow is:
2011-12-01 11:15:27. 745000
Original datetime 14:00:01 + 0700
Local datetime 15:00:01 +
>>>
When installing Python-dateutil, You must select the appropriate Python-dateutil version based on the Python version. Currently, Python-dateutil 1.5 is required for python2.x, python-dateutil 2.0 is for python3.x and cannot be used on python2.x.
Appendix:
Python-dateutil: http://labix.org/python-dateutil
Pytz: http://pytz.sourceforge.net/