【问题标题】:Convert a datetime to time with miliseconds in Python在 Python 中将日期时间转换为以毫秒为单位的时间
【发布时间】:2020-05-12 13:14:51
【问题描述】:

我有一个数据框:

client    datetime
1       01/02/2020 13:47
2       02/02/2020 23:45
3       03/02/2020 16:22
4       04/02/2020 18:49
5       05/02/2020 11:02

我需要两个新列 ["time_new"] 以这种格式显示时间 ('%H:%M:%S.%f')[:-3] 和 ["time_ms"] 以显示 ms仅:

client    datetime           time_new        time_ms
1       01/02/2020 13:47   13:47:11.783      783
2       02/02/2020 23:45   23:45:22.322      322
3       03/02/2020 16:22   16:22:05.122      122
4       04/02/2020 18:49   18:49:03.329      329
5       05/02/2020 11:02   11:02:34.545      545

【问题讨论】:

  • 在源数据帧中没有时间以秒和毫秒为单位?
  • 欢迎来到 SO!您可能会选择Tour,并且应该(重新)阅读帮助主题How to Ask 来设定您的期望。您至少应该自己尝试完成任务并在此处共享代码。即使你对 Python 不太了解。

标签: python python-3.x pandas datetime


【解决方案1】:

要提取带有时间和毫秒的自定义格式,请使用:

df['datetime'] = pd.to_datetime(df['datetime'])
df['time_new'] = df['datetime'].dt.strftime('%H:%M:%S.%f').str[:-3]
df['time_ms'] = df['datetime'].dt.microsecond // 1000

#in source df are 0 second and milisecond, so output like this
print (df)
   client            datetime      time_new  time_ms
0       1 2020-01-02 13:47:00  13:47:00.000        0
1       2 2020-02-02 23:45:00  23:45:00.000        0
2       3 2020-03-02 16:22:00  16:22:00.000        0
3       4 2020-04-02 18:49:00  18:49:00.000        0
4       5 2020-05-02 11:02:00  11:02:00.000        0

【讨论】:

    猜你喜欢
    • 2017-05-28
    • 2022-11-27
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 2014-03-14
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    相关资源
    最近更新 更多