Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing string to datetime while accounting for AM/PM in pandas

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

like image 833
C.Lee Avatar asked Jul 08 '18 20:07

C.Lee


People also ask

How do I convert string to datetime in Python AM PM?

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 .

How do I convert a string to a date in pandas?

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.

How do I show time in AM PM in Python?

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.

What is the method in pandas to change values into date time data type?

Code #1 : Convert Pandas dataframe column type from string to datetime format using pd. to_datetime() function.


1 Answers

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.

like image 121
cs95 Avatar answered Oct 28 '22 22:10

cs95