pandas.to_datetime — pandas 3.0.0.dev0+2095.g2e141aaf99 documentation (original) (raw)

pandas.to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, utc=False, format=None, exact=<no_default>, unit=None, origin='unix', cache=True)[source]#

Convert argument to datetime.

This function converts a scalar, array-like, Series orDataFrame/dict-like to a pandas datetime object.

Parameters:

argint, float, str, datetime, list, tuple, 1-d array, Series, DataFrame/dict-like

The object to convert to a datetime. If a DataFrame is provided, the method expects minimally the following columns: "year","month", "day". The column “year” must be specified in 4-digit format.

errors{‘raise’, ‘coerce’}, default ‘raise’

dayfirstbool, default False

Specify a date parse order if arg is str or is list-like. If True, parses dates with the day first, e.g. "10/11/12"is parsed as 2012-11-10.

Warning

dayfirst=True is not strict, but will prefer to parse with day first.

yearfirstbool, default False

Specify a date parse order if arg is str or is list-like.

Warning

yearfirst=True is not strict, but will prefer to parse with year first.

utcbool, default False

Control timezone-related parsing, localization and conversion.

See also: pandas general documentation about timezone conversion and localization.

formatstr, default None

The strftime to parse time, e.g. "%d/%m/%Y". Seestrftime documentation for more information on choices, though note that "%f" will parse all the way up to nanoseconds. You can also pass:

Note

If a DataFrame is passed, then format has no effect.

exactbool, default True

Control how format is used:

Cannot be used alongside format='ISO8601' or format='mixed'.

unitstr, default ‘ns’

The unit of the arg (D,s,ms,us,ns) denote the unit, which is an integer or float number. This will be based off the origin. Example, with unit='ms' and origin='unix', this would calculate the number of milliseconds to the unix epoch start.

originscalar, default ‘unix’

Define the reference date. The numeric values would be parsed as number of units (defined by unit) since this reference date.

cachebool, default True

If True, use a cache of unique, converted dates to apply the datetime conversion. May produce significant speed-up when parsing duplicate date strings, especially ones with timezone offsets. The cache is only used when there are at least 50 values. The presence of out-of-bounds values will render the cache unusable and may slow down parsing.

Returns:

datetime

If parsing succeeded. Return type depends on input (types in parenthesis correspond to fallback in case of unsuccessful timezone or out-of-range timestamp parsing):

Raises:

ParserError

When parsing a date from string fails.

ValueError

When another datetime conversion error happens. For example when one of ‘year’, ‘month’, day’ columns is missing in a DataFrame, or when a Timezone-aware datetime.datetime is found in an array-like of mixed time offsets, and utc=False, or when parsing datetimes with mixed time zones unless utc=True. If parsing datetimes with mixed time zones, please specify utc=True.

Notes

Many input types are supported, and lead to different output types:

The following causes are responsible for datetime.datetime objects being returned (possibly inside an Index or a Series withobject dtype) instead of a proper pandas designated type (Timestamp, DatetimeIndex or Serieswith datetime64 dtype):

Examples

Handling various input formats

Assembling a datetime from multiple columns of a DataFrame. The keys can be common abbreviations like [‘year’, ‘month’, ‘day’, ‘minute’, ‘second’, ‘ms’, ‘us’, ‘ns’]) or plurals of the same

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[s]

Using a unix epoch time

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')

Warning

For float arg, precision rounding might happen. To prevent unexpected behavior use a fixed-width exact type.

Using a non-unix epoch origin

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)

Differences with strptime behavior

"%f" will parse all the way up to nanoseconds.

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')

Non-convertible date/times

Passing errors='coerce' will force an out-of-bounds date to NaT, in addition to forcing non-dates (or non-parseable dates) to NaT.

pd.to_datetime("invalid for Ymd", format="%Y%m%d", errors="coerce") NaT

Timezones and time offsets

The default behaviour (utc=False) is as follows:

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[s]', freq=None)

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[s, UTC-05:00]', freq=None)

pd.to_datetime( ... ["2020-10-25 02:00 +0200", "2020-10-25 04:00 +0100"] ... )
ValueError: Mixed timezones detected. Pass utc=True in to_datetime or tz='UTC' in DatetimeIndex to convert to a common timezone.

import datetime as dt ser = pd.Series(["2020-10-25 02:00 +0200", "2020-10-25 04:00 +0100"]) ser.apply(lambda x: dt.datetime.strptime(x, "%Y-%m-%d %H:%M %z")) 0 2020-10-25 02:00:00+02:00 1 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)] ... )
ValueError: Mixed timezones detected. Pass utc=True in to_datetime or tz='UTC' in DatetimeIndex to convert to a common timezone.

Setting utc=True solves most of the above issues:

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[s, UTC]', freq=None)

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[s, 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[us, UTC]', freq=None)