转换为datetime

问题描述 投票:-1回答:4

我是Python的初学者。我将数据转换为日期时间格式时遇到问题。在DTNAISS专栏中,我有:

0    1972-12-22
1    1936-04-01
2    1925-10-05
3    1926-07-09
4    1952-01-12
5    1964-12-31
6    1940-01-13
7    1942-09-01
8    1939-01-12
9    1954-04-14
10   0001-01-01
11   1944-04-18
12   0001-01-01
13   1932-11-16
14   1936-05-18
15   1936-07-02
16   1944-01-13
17   1954-06-20
18   1927-02-14
19   1938-04-29
20   0001-01-01

当我尝试用日期时间改变它:test = pd.to_datetime(T_Client.DTNAIPRS.values)

我有这个错误:

>Traceback (most recent call last):
  File "/tmp/zeppelin_pyspark-6081451798601516313.py", line 349, in <module>
    raise Exception(traceback.format_exc())
Exception: Traceback (most recent call last):
  File "/tmp/zeppelin_pyspark-6081451798601516313.py", line 342, in <module>
    exec(code)
  File "<stdin>", line 4, in <module>
  File "/misc/anaconda2-4.4.0/envs/dev2/lib/python2.7/site-packages/pandas/core/tools/datetimes.py", line 380, in to_datetime
    result = _convert_listlike(arg, box, format)
  File "/misc/anaconda2-4.4.0/envs/dev2/lib/python2.7/site-packages/pandas/core/tools/datetimes.py", line 306, in _convert_listlike
    raise e
OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1-01-01 00:00:00

请问你能帮帮我吗 ?谢谢

python pandas python-datetime
4个回答
0
投票

您的问题是您的列包含(奇怪的)日期,无法在基础pd.Timestamp类型中表示,因为它是从numpy datetime64类型派生的(有关详细信息,请参阅Manoj Kumar's answer)。

一种简单的方法是在转换之前过滤掉这些值:

pd.to_datetime(T_Client.DTNAIPRS.where(T_Client.DTNAIPRS>='1677-09-22'))

1
投票

由于pandas表示以纳秒分辨率表示的时间戳,因此使用64位整数表示的时间跨度限制为大约584年

你的日期值超出范围1-01-01 00:00:00所以它是超出界限的错误。

In [92]: pd.Timestamp.min
Out[92]: Timestamp('1677-09-21 00:12:43.145225')

In [93]: pd.Timestamp.max
Out[93]: Timestamp('2262-04-11 23:47:16.854775807')

Refer hereOut of bounds


0
投票

这是一步一步的

import pandas as pd
import numpy as np

d = ['1972-12-22','1936-04-01','1925-10-05','1926-07-09','1952-01-12']
df = pd.DataFrame({'dates' :d})
df['dates'] = df['dates'].astype(pd.datetime)
df['dates'].dtype
df2 = pd.to_datetime(df['dates'])
print(df2)

这是在谷歌Colab尝试,我认为这是你正在寻找Working Output

如果您遇到任何其他问题,请与我们联系。


0
投票

我正在使用此代码将str转换为时间。首先应用你想要的格式,在我的情况下,你可以插入yyyy-mm-dd的小时/分钟/秒

然后选择需要更改的列并将.dt.time更改为.dt.date

frmt= '%H:%M:%S'
df['column name'] = pd.to_datetime(df['column name'],format=frmt).dt.time

祝好运

© www.soinside.com 2019 - 2024. All rights reserved.