I am trying to parse a string in this format "2018 - 07 - 07 04 - AM"
to pandas datetime using strftime format. However, It seems to me the format doesn't recognize the difference between AM
and PM
.
Here is what I tried:
pd.to_datetime("2018 - 07 - 07 04 - PM", format='%Y - %m - %d %H - %p').timestamp()
Out[4]: 1530936000.0
pd.to_datetime("2018 - 07 - 07 04 - AM", format='%Y - %m - %d %H - %p').timestamp()
Out[5]: 1530936000.0
Notice how the AM
and PM
are different in the above two strings, yet the same timeStamp is returned.
Pandas version: 0.23.3
Python version: 3.5.4
Use strptime() function of a datetime class Use datetime. strptime(date_string, format) to convert a given string into a datetime object as per the corresponding format .
Use pandas.to_datetime() method is used to change String/Object time to date type (datetime64[ns]). This method is smart enough to change different formats of the String date column to date.
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 format code for 24-hour time is %H:%M whereas the format for 12-hour time is %I:%M with %p appended if the time contains AM/PM.
Code #1 : Convert Pandas dataframe column type from string to datetime format using pd. to_datetime() function.
Since you're parsing a 12-hour time format, you will need %I
instead of %H
, otherwise the %p
specifier has no effect.
pd.to_datetime("2018 - 07 - 07 04 - PM", format='%Y - %m - %d %I - %p')
Timestamp('2018-07-07 16:00:00')
This behaviour is documented in the docs:
When used with the
strptime()
function, the%p
directive only affects the output hour field if the%I
directive is used to parse the hour.
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