[PYTHON] [Addition] Convert the time stamp including the English name of the month to datetime

Processing timestamps including Jan, Feb, ... etc

When writing the code to sort the data in chronological order, it took a lot of time to process the time stamp including the English name of the month, so make a note.

I want to convert the time stamp to a datetime object in order to compare the times, but the time stamp including English names such as Jan and Feb cannot be converted as it is.

Therefore, the calendar module is used to correspond the English name and the month.

test.py


import datetime
import calendar

timestamp = "Dec 3 14:55:51"
words = timestamp.split(" ")
months = {}
for i ,v in enumerate(calendar.month_abbr):
    months[v] = i
time_string = "2015-" + str(months[words[0]]) + "-" + str(words[1]) + " " + words[2]
time_datetime = datetime.datetime.strptime(time_string, '%Y-%m-%d %H:%M:%S')

This will successfully create a datetime object. It's not versatile because it has a great sense of decisiveness, but it's a memo.

Postscript

As you pointed out in the comments, it seems that the datetime document has a conversion from the English name of the month. I overlooked it. 8.1.7. Behavior of strftime () and strptime ()

In addition, we received information that python-dateutil will solve the era name as appropriate. Thank you very much.

reference

Convert string <-> date (datetime) in Python Place of Python English abbreviation month name (Jan, Feb, Mar, Apr…)

Recommended Posts

[Addition] Convert the time stamp including the English name of the month to datetime
Convert "number" of excel date to python datetime
To get the name of the primitive etc. generated immediately before
Determine the date and time format in Python and convert to Unixtime
I want to get the name of the function / method being executed
[Python] How to get the first and last days of the month
I want to output the beginning of the next month with Python
For the time being, I want to convert files with ffmpeg !!
Convert the result of python optparse to dict and utilize it
[Python] How to make the file name of the output data unique (use year, month, day, hour, second)