简体   繁体   English

将日期时间00:00:00更改为24:00:00

[英]change datetime 00:00:00 to 24:00:00

I have hourly data which starts from 00 to 23 hour every day. 我有每小时的数据,每天从00到23小时开始。 What I am trying to do is to switch 00 to 24 of the prior day for every date. 我想做的是将每个日期的前一天的00切换为24。

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. 在此示例中,我想将“ 20DEC08:00:00:00”更改为“ 19DEC08:24:00:00”,并且我也希望将同一内容更改为21Dec08和22Dec08,依此类推,每隔00:00:00。

Is there a pythonic way to do this?? 有pythonic的方法可以做到这一点吗?

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. 由于DateTime不允许24小时(即从00:00:00-23:59:59开始),因此,我认为最好的方法是将字符串转换为日期时间,然后再转换回字符串。

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. 我不知道如何在实践中使用它,但是重新格式化很有趣。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM