Python: How to convert a string to datetime without knowing the format?

I have a field that comes in as a string and represents time. Sometimes it is after 12 hours, sometimes at 24 hours. Possible values:

  • 8:26
  • 8:26 a.m.
  • 13:27

Is there a function that will convert them to a time format, being smart? Option 1 does not have am, because it is in a 24-hour format, while option 2 has 0 in front of it, and option 3 is obviously in a 24-hour format. Is there a function in Python / lib that does:

time = func(str_time) 
+6
source share
2 answers

super short answer:

 from dateutil import parser parser.parse("8:36pm") >>>datetime.datetime(2015, 6, 26, 20, 36) parser.parse("18:36") >>>datetime.datetime(2015, 6, 26, 18, 36) 

Dateutil should be available for your python installation; don't need something big like pandas

If you want to extract time from a datetime object:

 t = parser.parse("18:36").time() 

which will give you a time object (if it helps you more). Or you can extract individual fields:

 dt = parser.parse("18:36") hours = dt.hour minute = dt.minute 
+13
source

there is one such function from pandas

 import pandas as pd d = pd.to_datetime('<date_string>') 
+2
source

Source: https://habr.com/ru/post/989787/


All Articles