pandas 在 Python 中将数字转换为时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30070548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:19:04  来源:igfitidea点击:

Convert number to time in Python

pythonpandasdatetime

提问by Donald

I have a large CSV-file with a column called TIME. It's written as 1318 and I would like to use Python/Pandas to convert the data as 13:18 and see it as time instead of int64.

我有一个很大的 CSV 文件,其中有一列名为 TIME。它写为 1318,我想使用 Python/Pandas 将数据转换为 13:18,并将其视为时间而不是 int64。

I've tried something like this but this is not what I want:

我试过这样的事情,但这不是我想要的:

df['TIME'] = pd.to_datetime(df['TIME'])

Because I get this:

因为我得到了这个:

    1970-01-01 00:00:00.000001318                           
    1970-01-01 00:00:00.000001041                              
    1970-01-01 00:00:00.000000853

Any ideas?

有任何想法吗?

回答by EdChum

If you pass a formatparam to to_datetimeyou will get the following:

如果您将格式参数传递给to_datetime您,您将获得以下信息:

In [111]:

t="1318"
pd.to_datetime(t, format='%H%M')
Out[111]:
Timestamp('1900-01-01 13:18:00')

However, I don't know if you want a default date here.

但是,我不知道您是否想要这里的默认日期。

回答by wim

Use the formatkeyword argument to pd.to_datetimemethod.

使用format关键字参数到pd.to_datetime方法。

It is a string with the usual strftimesyntax.

它是一个具有通常strftime语法的字符串。

回答by Dan

This might help:

这可能有帮助:

  def extractTime(l):
    tt = (l.split(' ')[1]).split('.')[1][-4:];
    return tt[:2] + ':' + tt[-2:];

    if __name__ == '__main__':
      l = "1970-01-01 00:00:00.000001318";
      print extractTime(l);

It will print out "13:18" for the test case.

它将打印出测试用例的“13:18”。