I have some time input in the format of '10:23:34 PM'
in string and I'd like to convert it to a datetime looking like '22:23:45'
. I'm using
datetime = posts['time'].apply(lambda x: datetime.strptime(x, '%I:%M:%S %p').strftime('%I:%M:%S'))
However, this seems to disregard the AM/PM markers, and all the info comes out as if the time was in the AM, ergo for the '10:23:34 PM'
input I get '10:23:34'
as output, but it should be '22:23:45'
. How can I fix this?
How do you convert AM PM to 24 hour time in python? datetime. strptime() function to convert the string to a datetime object, and then using the string method strftime() to output the time in 24-hour format.
The date-time default format is “YYYY-MM-DD”. Hence, December 8, 2020, in the date format will be presented as “2020-12-08”. The datetime format can be changed and by changing we mean changing the sequence and style of the format.
Use astype() to Change datetime to String Format You can use this if the date is already in the format you want it in string form. The below example returns the date as a string with format %Y/%m/%d . dtype of column ConvertedDate will be object ( string ).
You want %H
not %I
:
In [44]:
d='10:23:34 PM'
pd.to_datetime(d).strftime('%H:%M:%S')
Out[44]:
'22:23:34'
%I
returns the 12-hour clock format, you want %H
to return the 24-hour format, see the docs
I think you can do this without using apply
here:
datetime = pd.to_datetime(posts['time']).dt.strftime('%H:%M:%S')
Note this gives you strings rather than a datetime
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