When making a datetime type from a string and registering it in elasticsearch,
It was strange if I didn't specify the timezone.
It is the ``` memorandum``
that I went to at that time. I would like to know if there is an easier way.
--String format: YYYY-mm-dd HH: MM: SS + 0900
--Added + 0900
to the end (because it is UTC + 9 hours)
--Strptime () format: % Y-% m-% d% H:% M:% S% z
--% z
corresponds to timezone
Example
from datetime import datetime as dt
#String
time_str = "2020-11-22 18:00:00+0900"
#Datetime type including timezone
time_dt = dt.strptime(time_str, '%Y-%m-%d %H:%M:%S%z')
print(time_dt.tzinfo)
# UTC+09:00
fromisoformat()
Is available.
Since the ISO 8601 format contains time zone information in the format `+ HH: MM``` or
-HH: MM``` at the end,
The argument is a character string similar to that.
python
#String
time_str = '2020-09-12 12:22:30+09:00'
#Datetime type including timezone
time_dt = dt.fromisoformat(time_str)
print(time_dt.tzinfo)
# UTC+09:00
Set / get / convert / delete timezone with Python, datetime, pytz \ | note.nkmk.me
Recommended Posts