Home > Net >  How to convert time to AM/PM in Pandas?
How to convert time to AM/PM in Pandas?

Time:10-04

I'm working with a pandas series. Datetime object that I created in this format:

import pandas as pd
import numpy as np

raw_nyc = pd.read_csv('project.csv')
raw_nyc['pickup_datetime'] =  pd.to_datetime(raw_nyc['pickup_datetime'], format='%Y-%m-%d %H:%M:%S %Z')

Example of one entry in this format: 2010-04-15 20:58:29 00:00

I'm hoping to use the time within this object to create a new column that would output AM or PM. Ideally I would even break it down more. Something like AM, PM, evening and night. I am unsure how I can do this efficiently. Thank you!

CodePudding user response:

here is one way to do it

%p return you the AM or PM of the time

pd.to_datetime(raw_nyc['pickup_datetime']).dt.strftime('%p')

data_time = {'DateTime':['2019-01-01 12:32:39-04:00','2019-01-01 00:34:52-04:00','2019-01-01 21:01:02-04:00','2019-01-01 01:05:10-04:00','2019-01-01 01:01:11-04:00'],
            }
df=pd.DataFrame(data_time)

df['AM/PM'] = pd.to_datetime(df['DateTime']).dt.strftime('%p')

                     DateTime   AM/PM
0   2019-01-01 12:32:39-04:00   PM
1   2019-01-01 00:34:52-04:00   AM
2   2019-01-01 21:01:02-04:00   PM
3   2019-01-01 01:05:10-04:00   AM
4   2019-01-01 01:01:11-04:00   AM


CodePudding user response:

According to the strftime documentation, you can format a date with %p to extract AM/PM.

Directive Meaning Example
%p Locale’s equivalent of either AM or PM. AM, PM (en_US)

So if I understand correctly your expected output, use pandas.Series.dt.strftime and pandas.Series.map :

raw_nyc['pickup_datetime'] =  pd.to_datetime(raw_nyc['pickup_datetime'])

dico = {'AM': 'midnight to noon', 'PM': 'noon to midnight'}

raw_nyc['Col1'] = raw_nyc['pickup_datetime'].dt.strftime('%p')
raw_nyc['Col2'] = raw_nyc['pickup_datetime'].dt.strftime('%p').map(dico)

# Output :

print(raw_nyc)

            pickup_datetime Col1              Col2
0 2010-04-15 20:58:29 00:00   PM  noon to midnight
  • Related