【问题标题】:Python pandas date time, how to convert these dates to pandas datetime?Python pandas 日期时间,如何将这些日期转换为 pandas 日期时间?
【发布时间】:2019-02-23 22:45:35
【问题描述】:

我的日期格式为月、年:

82013

102013

但我希望它们成为常规的 pandas 日期时间。当我将这些日期插入 pd.datetime 我得到 ​​p>

1970-01-01 00:00:00.000082013

这是非常错误的。

非常感谢您的建议。

【问题讨论】:

  • 您能控制日期的创建方式吗?如果可能,应该在此代码的上游解决问题。

标签: python pandas date datetime


【解决方案1】:

正如 roganjosh 所说,如果您一开始就可以以更简单的格式获取日期会更好。但是,如果您对此感到困惑,只需告诉 pd.to_datetime 您期望的 format 即可。

dates = pd.Series(['82013', '102013'])
pd.to_datetime(dates, format='%m%Y')

【讨论】:

  • 这是一个很好的答案 (+1)。但是,如果它们是整数,您可能需要事先转换为字符串。
【解决方案2】:
df

     date
0   82013
1  102013

首先,使用str.extract 将月份和年份提取为单独的列:

u = df.date.astype(str).str.extract(r'^(?P<month>\d{1,2})(?P<year>\d{4})$', expand=True)

  month  year
0     8  2013
1    10  2013

现在,让pd.to_datetime 接管。

pd.to_datetime(u.assign(day=1))

0   2013-08-01
1   2013-10-01
dtype: datetime64[ns]

如果可能存在无效值,请使用

pd.to_datetime(u.assign(day=1), errors='coerce')

【讨论】:

    【解决方案3】:

    使用 Python 的标准 datetime 模块:

    Python 3.7.2 (default, Jan 16 2019, 19:49:22) 
    [GCC 8.2.1 20181215 (Red Hat 8.2.1-6)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from datetime import datetime
    >>> datetime.strptime('82013', '%m%Y')
    datetime.datetime(2013, 8, 1, 0, 0)
    >>> datetime.strptime('102013', '%m%Y')
    datetime.datetime(2013, 10, 1, 0, 0)
    >>>
    

    以这种方式生成的日期将设置为该月的第一天零时零分钟。

    【讨论】:

      猜你喜欢
      • 2016-01-27
      • 2023-03-17
      • 2022-12-21
      • 1970-01-01
      • 2016-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多