Reputation: 7218
I am reading a csv
file which has a time field as 3:50a
and 4:25p
. I need to convert this time values to 24 hour clock format as H:M
for this I am doing:
datetime.strptime(str(time_value), '%I:%M').strftime('%H:%M')
where time_value
is 3:50a
or 4:25p
. Now the problem is above line of code do not work because I have not inlucded the AM/PM
tag which is %p
in %I:%M
and that is because in the csv
file I am just getting a
for AM
and p
for PM
.
How can I deal with this situation. I need to convert the time_value to 24hr clock format. Thanks
Upvotes: 0
Views: 2154
Reputation: 21643
Add an 'm'
to the string you input to strptime
and put the %p
in its second argument,
>>> from datetime import datetime
>>> time_value = '3:50a'
>>> datetime.strptime(str(time_value)+'m', '%I:%M%p').strftime('%H:%M')
'03:50'
>>> time_value = '4:25p'
>>> datetime.strptime(str(time_value)+'m', '%I:%M%p').strftime('%H:%M')
'16:25'
Upvotes: 3