I have this code:
arr=pd.date_range(start='1/1/2021', end='12/31/2021 23:00:00', freq='h')
df = pd.DataFrame({'year': arr.year})
dg = pd.DataFrame({'month': arr.month})
dh = pd.DataFrame({'day': arr.day})
di = pd.DataFrame({'hour': arr.hour,'minute': arr.minute,'second': arr.second})
I would like to get a csv format with an hourly frequency like this: "day,month,year,hour am" or "day,month,year,hour pm"
CodePudding user response:
I think this may be what you are looking for
timevalue_12hour = time.strftime( "%I:%M %p", t )
this would convert a time from datetime 24 hours format to 12 hours, the %I would convert the hour from 23 to 11 and the %p would get you the AM/PM value.
CodePudding user response:
Construct a new DataFrame with columns as maps over the date range with different format masks:
df = pd.DataFrame({
"year": arr.map(lambda x: x.strftime("%Y")),
"month": arr.map(lambda x: x.strftime("%m")),
"day": arr.map(lambda x: x.strftime("%d")),
"hour pm": arr.map(lambda x: x.strftime("%H:%M:%S %p")),
})
Than save it to .csv
df.to_csv("path/to/file.csv", sep=",", index=False)
CodePudding user response:
For any time format that you want you can use .strftime
and then define the format you need. Check out this cheat sheet for possible options: https://strftime.org/
%I: Hour (12-hour clock) as a zero-padded decimal number.
%p: Locale’s equivalent of either AM or PM.
To get the format you want, this will do it:
arr.strftime('%d,%m,%Y,%I %p')
Output:
Index(['01,01,2021,12 AM', '01,01,2021,01 AM', '01,01,2021,02 AM',
'01,01,2021,03 AM', '01,01,2021,04 AM', '01,01,2021,05 AM',
'01,01,2021,06 AM', '01,01,2021,07 AM', '01,01,2021,08 AM',
'01,01,2021,09 AM',
...
'31,12,2021,02 PM', '31,12,2021,03 PM', '31,12,2021,04 PM',
'31,12,2021,05 PM', '31,12,2021,06 PM', '31,12,2021,07 PM',
'31,12,2021,08 PM', '31,12,2021,09 PM', '31,12,2021,10 PM',
'31,12,2021,11 PM'],
dtype='object', length=8760)
If you want to make that into a dataframe you can simply split it on the comma "," then convert to frame like this:
df = arr.strftime('%d,%m,%Y,%I %p').str.split(',', expand=True).to_frame(index=False)
df.columns = ['Day', 'Month', 'Year', 'Time']
Result:
Day Month Year Time
0 01 01 2021 12 AM
1 01 01 2021 01 AM
2 01 01 2021 02 AM
3 01 01 2021 03 AM
4 01 01 2021 04 AM
... ... ... ... ...
8755 31 12 2021 07 PM
8756 31 12 2021 08 PM
8757 31 12 2021 09 PM
8758 31 12 2021 10 PM
8759 31 12 2021 11 PM
8760 rows × 4 columns