Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将时间字符串格式化为100ms-Python_Python_Pandas - Fatal编程技术网

将时间字符串格式化为100ms-Python

将时间字符串格式化为100ms-Python,python,pandas,Python,Pandas,我有一个函数,可以将时间字符串的格式设置为最接近0.1秒。但是,当四舍五入到最接近的秒时,它不会格式化时间戳。我将在下面附上一个示例: 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(d

我有一个函数,可以将时间字符串的格式设置为最接近0.1秒。但是,当四舍五入到最接近的秒时,它不会格式化时间戳。我将在下面附上一个示例:

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)
输出:

预期:

                    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

您可以从日期取整
timestamp()
方法返回的值,并从中实例化一个新的
datetime
。我添加了一个示例,它要求从第二个字段更新到第二个字段

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)
其结果是:

                    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
                    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