pandas.to_datetime #

熊猫。to_datetime ( arg ,错误= 'raise' , dayfirst = False , Yearfirst = False , utc = False , format = None ,精确= _NoDefault.no_default ,单位= None , infer_datetime_format = _NoDefault.no_default , origin = 'unix' , cache =正确) [来源] #

将参数转换为日期时间。

此函数将标量、类似数组SeriesDataFrame类似 /dict 的数据转换为 pandas 日期时间对象。

参数
arg int、float、str、datetime、列表、元组、一维数组、系列、DataFrame/dict-like

要转换为日期时间的对象。如果DataFrame提供了 a,则该方法至少需要以下列:"year", "month", "day"。 “年份”列必须以 4 位数格式指定。

错误{'ignore', 'raise', 'coerce'}, 默认 'raise'
  • 如果'raise',则无效解析将引发异常。

  • 如果'coerce',则无效解析将被设置为NaT

  • 如果'ignore',则无效解析将返回输入。

dayfirst布尔值,默认 False

如果arg是 str 或类似列表,则指定日期解析顺序。如果True,则首先解析日期,例如"10/11/12" 解析为2012-11-10

警告

dayfirst=True并不严格,但更喜欢先解析日期。

yearfirst布尔值,默认 False

如果arg是 str 或类似列表,则指定日期解析顺序。

  • 如果True首先解析年份的日期,例如 "10/11/12"解析为2010-11-12.

  • 如果dayfirstyearfirst均为True则yearfirst位于前面(与 相同dateutil)。

警告

yearfirst=True并不严格,但更喜欢首先解析年份。

utc bool, 默认 False

控制与时区相关的解析、本地化和转换。

  • 如果,True该函数始终返回一个时区感知的 UTC 本地化TimestampSeriesDatetimeIndex为此,时区原始输入将 本地化为 UTC,而时区感知输入将转换为 UTC。

  • 如果False(默认),输入将不会被强制为 UTC。时区原生输入将保持幼稚,而时区感知输入将保留其时间偏移。混合偏移(通常是夏令时)存在限制,有关详细信息,请参阅示例部分。

警告

在 pandas 的未来版本中,解析具有混合时区的日期时间将引发错误,除非utc=True。请指定utc=True以选择新行为并消除此警告。要创建具有混合偏移量和 对象数据类型的系列,请使用applydatetime.datetime.strptime

另请参阅:pandas 有关时区转换和本地化的一般文档。

格式str,默认无

解析时间的 strftime,例如"%d/%m/%Y"。有关选择的更多信息,请参阅 strftime 文档"%f",但请注意,它将一直解析到纳秒。您还可以通过:

  • “ISO8601”,解析任何ISO8601 时间字符串(不一定格式完全相同);

  • “混合”,单独推断每个元素的格式。这是有风险的,你应该将它与dayfirst一起使用。

笔记

如果DataFrame传递了 a,则format无效。

精确布尔值,默认 True

控制格式的使用方式:

  • 如果True,则需要精确的格式匹配。

  • 如果False,则允许格式匹配目标字符串中的任何位置。

不能与format='ISO8601'或一起使用format='mixed'

单位str,默认'ns'

arg (D,s,ms,us,ns) 的单位表示单位,可以是整数或浮点数。这将基于原点。例如,使用unit='ms'origin='unix',这将计算距 Unix 纪元开始的毫秒数。

infer_datetime_format bool, 默认 False

如果True没有给出格式,则尝试根据第一个非 NaN 元素推断日期时间字符串的格式,如果可以推断,则切换到更快的解析方法。在某些情况下,这可以将解析速度提高约 5-10 倍。

自 version 2.0.0 起已弃用:此参数的严格版本现在是默认值,传递它没有任何效果。

原点标量,默认“unix”

定义参考日期。数值将被解析为自该参考日期以来的单位数(由unit定义)。

  • 如果'unix'(或 POSIX)时间;原点设置为 1970-01-01。

  • 如果'julian',单位必须是'D',并且原点设置为儒略历的开始。儒略日编号0指定为从公元前 4713 年 1 月 1 日中午开始的那一天。

  • 如果 Timestamp 可转换(Timestamp、dt.datetime、np.datetimt64 或日期字符串),则 origin 将设置为由 origin 标识的时间戳。

  • unit如果是浮点或整数,则原点是相对于 1970-01-01 的差值(单位由参数确定)。

缓存布尔值,默认 True

如果True,则使用唯一的已转换日期的缓存来应用日期时间转换。解析重复的日期字符串时,尤其是具有时区偏移量的字符串时,可能会产生显着的加速。仅当至少有 50 个值时才使用缓存。越界值的存在将使缓存无法使用,并可能减慢解析速度。

返回
约会时间

如果解析成功。返回类型取决于输入(括号中的类型对应于时区失败或时间戳解析超出范围时的回退):

加薪
解析器错误

从字符串解析日期失败时。

值错误

当另一个日期时间转换错误发生时。例如,当 a 中缺少“年”、“月”、日”列之一时,或者在混合时间偏移的类似数组中找到DataFrame时区感知时,和。datetime.datetimeutc=False

也可以看看

DataFrame.astype

将参数转换为指定的数据类型。

to_timedelta

将参数转换为 timedelta。

convert_dtypes

转换数据类型。

笔记

支持多种输入类型,并导致不同的输出类型:

  • 标量可以是 int、float、str、datetime 对象(来自 stdlibdatetime 模块或numpy)。如果可能,它们将转换为Timestamp,否则将转换为datetime.datetime. None/NaN/null 标量转换为NaT.

  • 类似数组可以包含 int、float、str、datetime 对象。如果可能,它们将转换为 dtype DatetimeIndex,否则将转换为Indexdtype object,包含 datetime.datetime. None/NaN/null 条目NaT在两种情况下都会转换为 。

  • 如果可能,系列将转换为Seriesdtype datetime64 ,否则将转换为Seriesdtype object,包含datetime.datetime. None/NaN/null 条目NaT在两种情况下都会转换为。

  • DataFrame/dict-like转换为Seriesdtype datetime64。对于每一行,通过组装各个数据帧列来创建日期时间。列键可以是常见的缩写,例如 ['year', 'month', 'day', 'min', 'second', 'ms', 'us', 'ns'])或其复数形式。

以下原因导致datetime.datetime对象被返回(可能在 anIndex或 a Serieswith dtype 内) ,object而不是正确的 pandas 指定类型(TimestampDatetimeIndexwith dtype):Seriesdatetime64

  • 当任何输入元素位于之前Timestamp.min或之后 时Timestamp.max,请参阅时间戳限制

  • utc=False(默认)并且输入是类似数组或 Series包含混合天真/感知日期时间,或感知混合时间偏移量时。请注意,当时区有夏令时政策时,这种情况会(非常频繁)发生。在这种情况下,您可能希望使用utc=True.

例子

处理各种输入格式

从 的多列组装日期时间DataFrame。键可以是常见的缩写,例如 ['year', 'month', 'day', 'min', 'second', 'ms', 'us', 'ns']) 或相同的复数形式

>>> df = pd.DataFrame({'year': [2015, 2016],
...                    'month': [2, 3],
...                    'day': [4, 5]})
>>> pd.to_datetime(df)
0   2015-02-04
1   2016-03-05
dtype: datetime64[ns]

使用 Unix 纪元时间

>>> pd.to_datetime(1490195805, unit='s')
Timestamp('2017-03-22 15:16:45')
>>> pd.to_datetime(1490195805433502912, unit='ns')
Timestamp('2017-03-22 15:16:45.433502912')

警告

对于 float arg,可能会发生精度舍入。为了防止意外行为,请使用固定宽度的精确类型。

使用非 UNIX 纪元起源

>>> pd.to_datetime([1, 2, 3], unit='D',
...                origin=pd.Timestamp('1960-01-01'))
DatetimeIndex(['1960-01-02', '1960-01-03', '1960-01-04'],
              dtype='datetime64[ns]', freq=None)

与 strptime 行为的差异

"%f"将解析一直到纳秒。

>>> pd.to_datetime('2018-10-26 12:00:00.0000000011',
...                format='%Y-%m-%d %H:%M:%S.%f')
Timestamp('2018-10-26 12:00:00.000000001')

不可转换的日期/时间

除了强制将非日期(或不可解析的日期)强制为 之外,传递errors='coerce'还将强制将越界日期强制为。NaTNaT

>>> pd.to_datetime('13000101', format='%Y%m%d', errors='coerce')
NaT

时区和时间偏移

默认行为 ( utc=False) 如下:

>>> pd.to_datetime(['2018-10-26 12:00:00', '2018-10-26 13:00:15'])
DatetimeIndex(['2018-10-26 12:00:00', '2018-10-26 13:00:15'],
              dtype='datetime64[ns]', freq=None)
  • 具有恒定时间偏移的时区感知输入将转换为时区感知DatetimeIndex

>>> pd.to_datetime(['2018-10-26 12:00 -0500', '2018-10-26 13:00 -0500'])
DatetimeIndex(['2018-10-26 12:00:00-05:00', '2018-10-26 13:00:00-05:00'],
              dtype='datetime64[ns, UTC-05:00]', freq=None)
  • 但是,具有混合时间偏移的时区感知输入(例如从具有夏令时的时区发出,例如欧洲/巴黎)不会成功转换DatetimeIndex.解析具有混合时区的日期时间将显示警告,除非 utc=True。如果指定utc=False,将显示以下警告,并 返回一个简单的Index包含对象:datetime.datetime

>>> pd.to_datetime(['2020-10-25 02:00 +0200',
...                 '2020-10-25 04:00 +0100'])  
FutureWarning: In a future version of pandas, parsing datetimes with mixed
time zones will raise an error unless `utc=True`. Please specify `utc=True`
to opt in to the new behaviour and silence this warning. To create a `Series`
with mixed offsets and `object` dtype, please use `apply` and
`datetime.datetime.strptime`.
Index([2020-10-25 02:00:00+02:00, 2020-10-25 04:00:00+01:00],
      dtype='object')
>>> from datetime import datetime
>>> pd.to_datetime(["2020-01-01 01:00:00-01:00",
...                 datetime(2020, 1, 1, 3, 0)])  
FutureWarning: In a future version of pandas, parsing datetimes with mixed
time zones will raise an error unless `utc=True`. Please specify `utc=True`
to opt in to the new behaviour and silence this warning. To create a `Series`
with mixed offsets and `object` dtype, please use `apply` and
`datetime.datetime.strptime`.
Index([2020-01-01 01:00:00-01:00, 2020-01-01 03:00:00], dtype='object')

设置utc=True解决了上述大部分问题:

  • 时区原始输入本地化为 UTC

>>> pd.to_datetime(['2018-10-26 12:00', '2018-10-26 13:00'], utc=True)
DatetimeIndex(['2018-10-26 12:00:00+00:00', '2018-10-26 13:00:00+00:00'],
              dtype='datetime64[ns, UTC]', freq=None)
  • 时区感知输入将转换为 UTC(输出表示完全相同的日期时间,但从 UTC 时间偏移+00:00进行查看)。

>>> pd.to_datetime(['2018-10-26 12:00 -0530', '2018-10-26 12:00 -0500'],
...                utc=True)
DatetimeIndex(['2018-10-26 17:30:00+00:00', '2018-10-26 17:00:00+00:00'],
              dtype='datetime64[ns, UTC]', freq=None)
  • 输入可以包含字符串或日期时间,上述规则仍然适用

>>> pd.to_datetime(['2018-10-26 12:00', datetime(2020, 1, 1, 18)], utc=True)
DatetimeIndex(['2018-10-26 12:00:00+00:00', '2020-01-01 18:00:00+00:00'],
              dtype='datetime64[ns, UTC]', freq=None)