Need to change 24:00 to 23:00 time for portion of data in Python

后端 未结 2 1328
灰色年华
灰色年华 2021-01-17 04:50

I have data for 2018 and 2017 that uses 24:00 hour times like this:

Hour Ending         X           Y       Z
12/31/2017 24:00    11452.16    1834.87 2856.94         


        
2条回答
  •  长情又很酷
    2021-01-17 05:17

    I don't know how your data is structured, but just iterate through it and splice the string (if it's a string) to see if '24' shows up in the 5th to last chars to the 3rd to last char. Then add one to the date using the datetime module.

    import datetime
    
    lines = ['12/31/2017 24:00', '12/31/2017 23:00', '12/30/2017 24:00']
    for line in lines:
        print('PREVIOUS : ' + line)
        # Convert a 24 hour to 0 hour
        if line[-5:-3] == '24':
            (date, time) = line.split()
            time = time[:-5] + '0' + time[-3:]
            date = datetime.datetime.strptime(date, '%m/%d/%Y') + datetime.timedelta(days=1)
            print('CHANGED  : ' + date.strftime('%m/%d/%Y') + ' ' + time)
        else:
            print('UNCHANGED: ' + line)
    

    output:

    PREVIOUS : 12/31/2017 24:00
    AFTER    : 01/01/2018 0:00
    PREVIOUS : 12/31/2017 23:00
    UNCHANGED: 12/31/2017 23:00
    PREVIOUS : 12/30/2017 24:00
    AFTER    : 12/31/2017 0:00
    

提交回复
热议问题