I have hourly data which starts from 00 to 23 hour every day. What I am trying to do is to switch 00 to 24 of the prior day for every date.
Here is an example data:
import pandas as pd
data = {'datetime' : ['19DEC08:22:00:00', '19DEC08:23:00:00', '20DEC08:00:00:00', '20DEC08:01:00:00', '20DEC08:02:00:00'],
'entry' : ['a','b','c','d','e']}
df = pd.DataFrame(data)
I this example, I want to change '20DEC08:00:00:00' to '19DEC08:24:00:00' and also, I want the same thing to 21Dec08 and 22Dec08 and so on for every 00:00:00.
Is there a pythonic way to do this??
Since DateTime doesn't allow a 24th hour (ie goes from 00:00:00 - 23:59:59), the best way I see to do this is to convert from string to datetime and back to string.
import calendar
def add_24th_hour(row):
date = row['datetime']
if date.hour == 00:
hour = 24
day = date.day -1
return "{:02d}{}{:02d}:{:02d}:{:02d}:{:02d}".format(day,
calendar.month_abbr[date.month],
date.year,
hour,
date.minute,
date.second)
else:
return "{:02d}{}{:02d}:{:02d}:{:02d}:{:02d}".format(date.day,
calendar.month_abbr[date.month],
date.year,
date.hour,
date.minute,
date.second)
df['datetime'] = pd.to_datetime(df['datetime'], format = '%d%b%y:%H:%M:%S')
df.loc[:,'24hr_datetime'] = df.apply(add_24th_hour, axis=1)
I don't see how this would be used in practice but it was interesting to reformat.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.