pandas.to_datetime#
- pandas.to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, utc=False, format=None, exact=_NoDefault.no_default, unit=None, infer_datetime_format=_NoDefault.no_default, origin='unix', cache=True)[源代码]#
将参数转换为 datetime。
此函数将标量、类数组、
Series或DataFrame类字典对象转换为 pandas datetime 对象。- Parameters:
- argint、float、str、datetime、list、tuple、一维数组、Series、DataFrame/类字典
要转换为 datetime 的对象。如果提供
DataFrame,则该方法至少需要以下列:"year""month""day"。列 “year” 必须以 4 位数字格式指定。- errors{‘ignore’, ‘raise’, ‘coerce’},默认为 ‘raise’
如果为
'raise',则无效的解析将引发异常。如果为
'coerce',则无效的解析将设置为NaT。如果为
'ignore',则无效的解析将返回输入。
- dayfirstbool,默认 False
如果 arg 是 str 或类列表,则指定日期解析顺序。如果为
True,则先解析日期中的日,例如"10/11/12"被解析为2012-11-10。警告
dayfirst=True不是严格的,但会优先按日解析。- yearfirstbool,默认 False
如果 arg 是 str 或类列表,则指定日期解析顺序。
如果为
True,则先解析日期中的年,例如"10/11/12"被解析为2010-11-12。如果 dayfirst 和 yearfirst 都为
True,则 yearfirst 优先(与dateutil相同)。
警告
yearfirst=True不是严格的,但会优先尝试按年份解析。- utcbool,默认 False
控制与时区相关的解析、本地化和转换。
如果为
True,则函数*始终*返回一个时区感知且已本地化为 UTC 的Timestamp、Series或DatetimeIndex。为此,需要将时区不明的输入*本地化*为 UTC,同时将时区感知的输入*转换为* UTC。如果为
False(默认值),则输入不会被强制转换为 UTC。时区不明的输入将保持不明,而时区感知的输入将保留其时间偏移。对于混合偏移(通常是夏令时),存在局限性,有关详细信息,请参阅 Examples 部分。
警告
在 pandas 的未来版本中,解析具有混合时区的日期时间将引发错误,除非指定 utc=True。请指定 utc=True 以选择加入新的行为并消除此警告。要创建具有混合偏移和 object 数据类型的 Series,请使用 apply 和 datetime.datetime.strptime。
另请参阅:pandas 关于 timezone conversion and localization 的通用文档。
- formatstr,默认 None
用于解析时间的 strftime 格式,例如
"%d/%m/%Y"。有关格式选择的更多信息,请参阅 strftime documentation ,但请注意,"%f"可以解析到纳秒。您也可以传递:“ISO8601”,用于解析任何 ISO8601 时间字符串(不一定是完全相同的格式);
“mixed”,用于单独推断每个元素的格式。这有风险,您可能应该与 dayfirst 一起使用它。
备注
如果传入
DataFrame,则 format 无效。- exactbool, default True
控制 format 的使用方式:
如果为
True,则要求完全匹配 format。如果为
False,则允许 format 匹配目标字符串中的任意位置。
不能与
format='ISO8601'或format='mixed'一起使用。- unitstr,默认为 ‘ns’
参数的单位(D,s,ms,us,ns)表示单位,它是一个整数或浮点数。这将基于原点。例如,如果使用
unit='ms'和origin='unix',这将计算自 Unix 纪元开始以来的毫秒数。- infer_datetime_formatbool,默认 False
如果为
True且未给出 format,则尝试根据第一个非 NaN 元素推断日期时间字符串的格式,如果可以推断,则切换到一种更快的解析方法。在某些情况下,这可以将解析速度提高约 5-10 倍。自 2.0.0 版本弃用: 该参数的严格版本现在是默认值,传递它没有效果。
- origin标量,默认为 ‘unix’
定义参考日期。数字将根据 unit 参数指定的单位数量解析为自此参考日期以来的值。
如果为
'unix'(或 POSIX) 时间;原点设置为 1970-01-01。如果为
'julian',则单位必须为'D',原点设置为儒略历的开始。儒略日号0分配给公元前 4713 年 1 月 1 日中午开始的那一天。如果为 Timestamp 可转换类型(Timestamp、dt.datetime、np.datetimt64 或日期字符串),则原点设置为由 origin 标识的 Timestamp。
如果为浮点数或整数,则原点是相对于 1970-01-01 的差值(以 unit 参数确定的单位表示)。
- cachebool, default True
如果为
True,则使用唯一的、已转换日期的缓存来应用日期时间转换。当解析重复的日期字符串(尤其是带有时区偏移的字符串)时,可能会显著提高速度。仅当值至少有 50 个时才使用缓存。出现超出范围的值将使缓存不可用,并可能减慢解析速度。
- Returns:
- datetime
如果解析成功。返回类型取决于输入(括号中的类型对应于在时区解析或超出范围的时间戳解析不成功的情况下的后备选项):
标量:
Timestamp(或datetime.datetime类数组:
DatetimeIndex(或包含Series的objectdtype 的datetime.datetimeSeries:
Seriesdtype 的datetime64(或包含Series的objectdtype 的datetime.datetimeDataFrame:
Seriesdtype 的datetime64(或包含Series的objectdtype 的datetime.datetime
- Raises:
- ParserError
当从字符串解析日期失败时。
- ValueError
当发生其他日期时间转换错误时。例如,当
DataFrame中缺少 ‘year’、’month’、’day’ 列之一时,或者当类UTC时间(Timezone-aware)的datetime.datetime出现在混合时间偏移量的类数组(array-like)中,并且设置了utc=False。
参见
DataFrame.astype将参数转换为指定的dtype。
to_timedelta将参数转换为 timedelta。
convert_dtypes转换dtype。
Notes
支持多种输入类型,并产生不同的输出类型:
标量(scalars) 可以是 int、float、str、datetime 对象(来自标准库
datetime模块或numpy)。它们尽可能转换为Timestamp,否则将转换为datetime.datetime。None/NaN/null 标量将转换为NaT。类数组(array-like) 可以包含 int、float、str、datetime 对象。它们尽可能转换为
DatetimeIndex,否则将转换为具有Indexdtype 的object,其中包含datetime.datetime对象。在这两种情况下,None/NaN/null 条目都将转换为NaT。Series 尽可能转换为具有
Seriesdtype 的datetime64,否则将转换为具有Seriesdtype 的object,其中包含datetime.datetime对象。在这两种情况下,None/NaN/null 条目都将转换为NaT。DataFrame/类字典(dict-like) 将转换为具有
Seriesdtype 的datetime64。对于每一行,通过组合 DataFrame 的各个列来创建一个 datetime。列键可以是常见的缩写,如 [‘year’, ‘month’, ‘day’, ‘minute’, ‘second’, ‘ms’, ‘us’, ‘ns’],或者它们的复数形式。
以下原因会导致返回
datetime.datetime对象(可能在Index或具有Seriesdtype 的object中),而不是 pandas 的指定类型(Timestamp、DatetimeIndex或具有Seriesdtype 的datetime64):当任何输入元素早于
Timestamp.min或晚于Timestamp.max时,请参阅 timestamp limitations 。当
utc=False``(默认)且输入是类数组或 :class:`Series` ,其中包含混合的时区Naive和时区aware的datetime,或具有混合时间偏移量的时区aware datetime。请注意,在(相当频繁的)时区具有夏令时政策的情况下也会发生这种情况。在这种情况下,您可能希望使用 ``utc=True。
Examples
处理各种输入格式
从
DataFrame的多个列组合 datetime。键可以是常见的缩写,如 [‘year’, ‘month’, ‘day’, ‘minute’, ‘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 epoch 时间
>>> 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 参数,可能会发生精度舍入。为防止意外行为,请使用固定宽度的精确类型。
使用非 Unix epoch 起点
>>> 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'将强制将超出范围的日期设置为NaT,此外还将非日期(或无法解析的日期)强制设置为NaT。>>> pd.to_datetime('13000101', format='%Y%m%d', errors='coerce') NaT
时区和时间偏移
默认行为(
utc=False)如下:时区Naive输入将转换为时区Naive的
DatetimeIndex:
>>> 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)
具有*恒定时间偏移*的时区aware输入将转换为时区aware的
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)
然而,具有*混合时间偏移*的时区aware输入(例如,来自具有夏令时的时区,如 Europe/Paris)**将无法成功转换为**
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')
混合时区aware和时区Naive输入也将转换为包含
Index对象的简单datetime.datetime:
>>> 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可以解决上述大多数问题:时区Naive输入被*本地化*为 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)
时区aware输入被*转换为* 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)