How to convert string to datetime format in pandas python? [ Complete Guide ]

Spread the love

If you want to convert a string to datetime, you can use inbuilt function in pandas data frame. That is pandas.to_datetime().

Syntax : pandas.to_datetime(arg, errors=’raise’, dayfirst=False, yearfirst=False, utc=None, box=True, format=None, exact=True, unit=None, infer_datetime_format=False, origin=’unix’, cache=False)

arg : integer, float, string, datetime, list, tuple, 1-d array, Series
New in version 0.18.1: or DataFrame/dict-like

errors : {‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’
If ‘raise’, then invalid parsing will raise an exception
If ‘coerce’, then invalid parsing will be set as NaT
If ‘ignore’, then invalid parsing will return the input
dayfirst : boolean, default False
Specify a date parse order if arg is str or its list-likes. If True, parses dates with the day first, eg 10/11/12 is parsed as 2012-11-10. Warning: dayfirst=True is not strict, but will prefer to parse with day first (this is a known bug, based on dateutil behavior).

yearfirst : boolean, default False
Specify a date parse order if arg is str or its list-likes.

If True parses dates with the year first, eg 10/11/12 is parsed as 2010-11-12.
If both dayfirst and yearfirst are True, yearfirst is preceded (same as dateutil).
Warning: yearfirst=True is not strict, but will prefer to parse with year first (this is a known bug, based on dateutil behavior).

New in version 0.16.1.

utc : boolean, default None
Return UTC DatetimeIndex if True (converting any tz-aware datetime.datetime objects as well).

box : boolean, default True
If True returns a DatetimeIndex or Index-like object
If False returns ndarray of values.
format : string, default None
strftime to parse time, eg “%d/%m/%Y”, note that “%f” will parse all the way up to nanoseconds.

exact : boolean, True by default
If True, require an exact format match.
If False, allow the format to match anywhere in the target string.
unit : string, default ‘ns’
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’ (the default), this would calculate the number of milliseconds to the unix epoch start.

infer_datetime_format : boolean, default False
If True and no format is given, attempt to infer the format of the datetime strings, and if it can be inferred, switch to a faster method of parsing them. In some cases this can increase the parsing speed by ~5-10x.

origin : scalar, default is ‘unix’
Define the reference date. The numeric values would be parsed as number of units (defined by unit) since this reference date.

If ‘unix’ (or POSIX) time; origin is set to 1970-01-01.
If ‘julian’, unit must be ‘D’, and origin is set to beginning of Julian Calendar. Julian day number 0 is assigned to the day starting at noon on January 1, 4713 BC.
If Timestamp convertible, origin is set to Timestamp identified by origin.

cache : boolean, default False
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.

ret : datetime if parsing succeeded.
Return type depends on input:

list-like: DatetimeIndex
Series: Series of datetime64 dtype
scalar: Timestamp
In case when it is not possible to return designated types (e.g. when any element of input is before Timestamp.min or after Timestamp.max) return will have datetime.datetime type (or corresponding array/Series).

Program Example:

import pandas as pd data_f = pd.Series(['1901/2/12','1901/2/13','1901/2/14']) data_mn = pd.Series(['1901/feb/12','1901/feb/13','1901/feb/14']) data_d = pd.Series(['1901feb12','1901feb13','1901feb14']) data_u = pd.Series(['1349720105','1349720105', '1349720105']) print(data_f) print(data_mn) print(data_d) print(data_u) data_f=pd.to_datetime(data_f, format='%Y%m%d', errors='ignore') data_mn=pd.to_datetime(data_mn, format='%Y%m%d', errors='ignore') data_d=pd.to_datetime(data_d, format='%Y%m%d', errors='ignore') data_u=pd.to_datetime('20181010', format='%Y%m%d', errors='ignore') print('after conversion') print(data_f) print(data_mn) print(data_d) print(data_u)