It's a memorandum because I was unexpectedly addicted to the pot. It seems to be easier, but once this is done.
What I want to do → I want to change the date (standard time) of the character string to Japan time
#This is all you need to import
import datetime
#Original date (standard time)
hiduke = '25/Aug/2020 11:01:52'
#1.Convert to date type
hiduke = datetime.datetime.strptime(hiduke, '%d/%b/%Y %H:%M:%S')
#2.Give time zone information (UTC here)
hiduke = hiduke.replace(tzinfo=datetime.timezone.utc)
#3.Convert time zone to Japan time
(+9 hours)
hiduke = hiduke.astimezone(datetime.timezone(datetime.timedelta(hours=+9)))
#4.Erase timezone notation
hiduke = hiduke.replace(tzinfo=None)
--strrptime = String (to be) Replace (ed by) Time seems to be connected.
--In the argument, specify the date (character string) you want to convert and the notation that the date is written.
--% d = day
--% b = month (Aug). Abbreviation for the name of the month. In the case of a number month,% m, in the case of August,% B
--% Y = year
--If it is 2020-08-26, it is written as % Y-% m-% d
.
--A list of notations can be found here.
Convert dates, times and strings with Python datetime (strftime, strptime)
tzinfo = timezone info.
Japan time is standard time + 9 hours. It becomes hours = + 9
. The actual notation is datetime.timedelta (hours = + 9)
If you leave it as ③, +09: 00
(time zone notation) will be attached after the date, so you can delete it by setting tzinfo = None
.
With this, 25 / Aug / 2020 11:01:52
becomes 2020-08-25 20:01:52
.
Set / Get / Convert / Delete timezone with Python, datetime, pytz
Convert string <-> date (datetime) in Python
Recommended Posts