【问题标题】:Convert string date time to pandas datetime将字符串日期时间转换为熊猫日期时间
【发布时间】:2017-05-20 23:33:30
【问题描述】:

我是 Pandas 和 Python 的新手。我想在我的脚本中做一些日期时间操作。 我从以下格式的 csv 文件中获取日期时间信息: 01APR2017 6:59

如何将其转换为 pandas 日期时间格式?就像是: 2017-04-01 06:59:00

【问题讨论】:

  • 有一个重复的问题here 很有帮助。

标签: python python-2.7 csv pandas datetime


【解决方案1】:

您可以将to_datetime 与参数format 一起使用:

s = pd.Series(['01APR2017 6:59','01APR2017 6:59'])

print (s)
0    01APR2017 6:59
1    01APR2017 6:59
dtype: object

print (pd.to_datetime(s, format='%d%b%Y %H:%M'))
0   2017-04-01 06:59:00
1   2017-04-01 06:59:00
dtype: datetime64[ns]

另一种可能的解决方案是在read_csv 中使用date_parser

import pandas as pd
from pandas.compat import StringIO

temp=u"""date
01APR2017 6:59
01APR2017 6:59"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
parser = lambda x: pd.datetime.strptime(x, '%d%b%Y %H:%M')
df = pd.read_csv(StringIO(temp), parse_dates=[0], date_parser=parser)

print (df)
                 date
0 2017-04-01 06:59:00
1 2017-04-01 06:59:00

print (df.date.dtype)
datetime64[ns]

通过评论编辑:

如果值无法解析为datetime,则添加参数errors='coerce'用于转换为NaT

s = pd.Series(['01APR2017 6:59','01APR2017 6:59', 'a'])
print (s)
0    01APR2017 6:59
1    01APR2017 6:59
2                 a
dtype: object

print (pd.to_datetime(s, format='%d%b%Y %H:%M', errors='coerce'))
0   2017-04-01 06:59:00
1   2017-04-01 06:59:00
2                   NaT
dtype: datetime64[ns]

【讨论】:

  • 感谢您的快速回复。我尝试了解决方案 #1,但出现以下错误 - ValueError: time data '01APR2017 6:59' does not match format '%d%b%y %H:%M' 该列 csv 中的某些字段不包含日期并且为空白/空
  • 嗨,Jezrael,问题似乎是我的专栏的 dtype 是浮动的。如何将其更改为对象类型?
  • 使用df['col'] = df['col'].astype(str),但如果数据类似于01APR2017 6:59,它是字符串,而不是浮点数。
猜你喜欢
  • 2022-06-29
  • 1970-01-01
  • 2021-07-28
  • 2016-03-24
  • 2015-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多