Python 2.7.10
8.1. datetime — basic date and time types
>>> from datetime import datetime
>>> import pytz
>>>
>>> jst = pytz.timezone('Japan')
>>> jst_datetime = datetime.now().replace(tzinfo=jst)
>>> print jst_datetime
2015-11-12 16:09:18.544266+09:00
>>> jst_datetime_str = datetime.strftime(jst_datetime, '%Y-%m-%d %H:%M:%S %z')
>>> print jst_datetime_str
2015-11-12 16:09:18 +0900
>>> datetime.strftime(jst_datetime, '%Y-%m-%d %H:%M:%S %Z')
'2015-11-12 16:09:18 JST'
It is possible to output a datetime character string with tzinfo.
>>> print jst_datetime_str
2015-11-12 16:09:18 +0900
>>> datetime.strptime(jst_datetime_str, '%Y-%m-%d %H:%M:%S %z')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/lib/python2.7/_strptime.py", line 317, in _strptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M:%S %z'
>>>
I tried to get the datetime with timsezone using the datetime string with tzinfo, but I got an error.
ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M:%S %z'
I get an error that the'% z'specifier is in a bad format.
The result of various investigations http://stackoverflow.com/questions/2609259/converting-string-to-datetime-object-in-python
It seems that% z is not supported in python2.7. It seems to work with python3.2. I can't change the version, so try another method
>>> jst_datetime_str = datetime.strftime(jst_datetime, '%Y-%m-%d %H:%M:%S %Z')
>>> print jst_datetime_str
2015-11-12 16:09:18 JST
>>> datetime.strptime(jst_datetime_str, '%Y-%m-%d %H:%M:%S %Z')
datetime.datetime(2015, 11, 12, 16, 9, 18)
I tried using% Z, but this time I get a datetime without tzinfo, although no error occurs.
Looking for others http://nekoya.github.io/blog/2013/06/21/python-datetime/
This person also couldn't use% Z, so it seems that he used "replace (tzinfo = pytz.utc)" to set it. It seems impossible to convert using a specifier, so I tried to handle it by pushing
>>> from datetime import datetime
>>> import pytz
>>>
>>> jst = pytz.timezone('Japan')
>>> jst_datetime = datetime.now().replace(tzinfo=jst)
>>> print jst_datetime
2015-11-12 16:54:19.564920+09:00
>>> jst_datetime_str = datetime.strftime(jst_datetime, '%Y-%m-%d %H:%M:%S') + ' ' + jst_datetime.tzinfo.zone
>>> print jst_datetime_str
2015-11-12 16:54:19 Japan
>>> zone = jst_datetime_str.split(' ')[-1]
>>> print zone
Japan
>>> datetime_str = ' '.join(jst_datetime_str.split(' ')[:2])
>>> print datetime_str
2015-11-12 16:54:19
>>> datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.timezone(zone))
datetime.datetime(2015, 11, 12, 16, 54, 19, tzinfo=<DstTzInfo 'Japan' JST+9:00:00 STD>)
Like this.
-In python2.7, the specifiers'% Z'and'% z'cannot be used in strptime. ・ However, it can be used normally with strftime. ・ I haven't confirmed it later, but it seems that python3.2 can be used with strptime. ・ Honestly, it feels like a force, but I wonder if there is any other good way.
Recommended Posts