I have a field that comes in as a string and represents a time. Sometimes its in 12 hour, sometimes in 24 hour. Possible values:
Is there a function that will convert these to time format by being smart about it? Option 1 doesn't have am because its in 24 hour format, while option 2 has a 0 before it and option 3 is obviously in 24 hour format. Is there a function in Python/ a lib that does:
time = func(str_time)
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; no need for something large like pandas
If you want to extract the time from the datetime
object:
t = parser.parse("18:36").time()
which will give you a time
object (if that's of more help to you).
Or you can extract individual fields:
dt = parser.parse("18:36")
hours = dt.hour
minute = dt.minute
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With