Home > Enterprise >  What's the most efficient way to convert a string like "3:00pm" to a Python datetime
What's the most efficient way to convert a string like "3:00pm" to a Python datetime

Time:10-27

I have a column of times that are stored as strings. What I would like to do is take "3:00pm" and convert it to a datetime object that's 15:00 (24 hour clock).

I could always write a custom function that parses out the string, identifies whether it's am or pm, and create a mapping, but I was wondering if there's any built in functionality in Python or Pandas to do this efficiently.

Thanks so much!

CodePudding user response:

Considering the following dataframe as an example

      Time  Value
0   7:00pm     48
1   8:00pm     48
2  11:00am      8
3   5:00pm      8
4  12:00pm     62
5   8:00am     41
6   9:00am     51
7   7:00pm     70
8   6:00am     41
9   5:00am     72

In order to convert the column Time from 3:00pm to a datetime object that's 15:00 (24 hour clock), one can use pandas.to_datetime as follows

df['Time'] = pd.to_datetime(df['Time'], format = '%I:%M%p')

[Out]:

                 Time  Value
0 1900-01-01 19:00:00     48
1 1900-01-01 20:00:00     48
2 1900-01-01 11:00:00      8
3 1900-01-01 17:00:00      8
4 1900-01-01 12:00:00     62
5 1900-01-01 08:00:00     41
6 1900-01-01 09:00:00     51
7 1900-01-01 19:00:00     70
8 1900-01-01 06:00:00     41
9 1900-01-01 05:00:00     72

Notes:

CodePudding user response:

here is one way to do it

# convert to datetime and gather the time
df['24hr']=pd.to_datetime(df['Time']).dt.time
df
    Time    24hr
0   7:00pm  19:00:00
1   8:00pm  20:00:00
2   11:00am 11:00:00
3   3:00am  03:00:00
4   1:00pm  13:00:00
  • Related