简体   繁体   中英

Format time strings to 100ms - Python

I have a function that formats time strings to the nearest 0.1 of a second. However, it doesn't format timestamps when rounding up to the nearest second. I'll attach an example below:

d = ({                            
    'Time' : ['2019-08-02 09:50:19.880','2019-08-02 09:50:19.970','2019-08-02 09:50:19.980','2019-08-02 09:50:20.070'],
    })

df = pd.DataFrame(data = d)

def format_time(col):
    col = pd.to_datetime(col)
    t = col    
    s = t.strftime('%Y-%m-%d %H:%M:%S.%f')
    tail = s[-8:]
    f = round(float(tail), 3)
    temp = "%.1f" % f
    return "%s%s" % (s[:-8], temp[0:])

df['Time'] = df['Time'].apply(format_time)

Out:

                     Time
0   2019-08-02 09:50:19.9
1  2019-08-02 09:50:110.0
2  2019-08-02 09:50:110.0
3   2019-08-02 09:50:20.1

Intended:

                    Time
0   2019-08-02 09:50:19.9
1   2019-08-02 09:50:20.0
2   2019-08-02 09:50:20.0
3   2019-08-02 09:50:20.1

You could round the value returned by the timestamp() method from the date and instantiate a new datetime from it. I have added an example which requires updating all the fields, from the second to the year.

import datetime

d = ({                            
    'Time' : ['2019-08-02 09:50:19.880',
              '2019-08-02 09:50:19.970',
              '2019-08-02 09:50:19.980',
              '2019-08-02 09:50:20.070',
              '2019-08-02 09:50:20.320',
              '2019-12-31 23:59:59.990'
             ],
    })

df = pd.DataFrame(data = d)

def format_time(col):
    t = pd.to_datetime(col)      
    t = datetime.datetime.fromtimestamp(round(t.timestamp(), 1))
    return t.strftime('%Y-%m-%d %H:%M:%S.%f')[:-5]

df['Time'] = df['Time'].apply(format_time)
print(df)

which results in:

                    Time
0  2019-08-02 09:50:19.9
1  2019-08-02 09:50:20.0
2  2019-08-02 09:50:20.0
3  2019-08-02 09:50:20.1
4  2019-08-02 09:50:20.3
5  2020-01-01 00:00:00.0

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.

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