Pandas pd.to_datatime

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html

Examples


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

If a date does not meet the `timestamp limitations

<http://pandas.pydata.org/pandas-docs/stable/timeseries.html

#timeseries-timestamp-limits>`_, passing errors='ignore'

will return the original input instead of raising any exception.

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('13000101', format='%Y%m%d', errors='ignore')

datetime.datetime(1300, 1, 1, 0, 0)

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

NaT

Passing infer_datetime_format=True can often-times speedup a parsing

if its not an ISO8601 format exactly, but in a regular format.

>>> s = pd.Series(['3/11/2000', '3/12/2000', '3/13/2000']*1000)

>>> s.head()

0    3/11/2000

1    3/12/2000

2    3/13/2000

3    3/11/2000

4    3/12/2000

dtype: object     

>>> %timeit pd.to_datetime(s,infer_datetime_format=True)

100 loops, best of 3: 10.4 ms per loop

>>> %timeit pd.to_datetime(s,infer_datetime_format=False)

1 loop, best of 3: 471 ms per loop

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

0    1960-01-02

1    1960-01-03

2    1960-01-04


Parameters

----------

arg : integer, float, string, datetime, list, tuple, 1-d array, Series

    .. versionadded:: 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 beahavior).

    .. versionadded:: 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

    - 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.

.. versionadded:: 0.20.0

cache : boolean, default False

    If True, use a cache of unique, converted dates to apply the datetime

    conversion. May produce sigificant speed-up when parsing duplicate date

    strings, especially ones with timezone offsets.

    .. versionadded:: 0.23.0

Returns

-------

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,386评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,142评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,704评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,702评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,716评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,573评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,314评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,230评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,680评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,873评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,991评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,706评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,329评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,910评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,038评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,158评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,941评论 2 355

推荐阅读更多精彩内容

  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,456评论 0 13
  • Overview The ccxt library is a collection of available cr...
    郭蝈儿蝈儿阅读 3,718评论 0 1
  • 在连接的时代,是一个机会更多,概率更小的世界,处处有机会,就是处处有竞争。深思熟虑后做选择的战略能力,行动...
    Arielth阅读 333评论 0 0
  • 简书里我是不是可以随便写,写什么都可以?包括我丢失的记忆,憧憬的未来,还有当下的人与事。 简书里是不是每个人都会和...
    向日葵的野风和陌路阅读 166评论 0 1
  • java代码 代码中定义一个WebView类对象,然后通过addJavascriptInterface注册了一个名...
    sakuradream阅读 1,248评论 0 0