Search code examples
pythonpython-3.xdatetimestrptime

Strptime presumes hours inconsistently


I have a (pandas) Series of numbers like

20170809
20181231

I want to convert them into datetime objects. this is trivial with an apply wrapped around datetime.strptime(x, '%Y%M%d'). However, datetime is adding on hours that are different. For instance:

 20011231 2001-01-31 00:12:00
 20050102 2005-01-02 00:01:00
 20000815 2000-01-15 00:08:00

How can I force strptime to assume the same hour/minute/second for every string?


Solution

  • The month is m. The capital M means minute.

    You do:

    >>> datetime.strptime('20011231', '%Y%M%d')
    datetime.datetime(2001, 1, 31, 0, 12)
    

    but need to do:

    >>> datetime.strptime('20011231', '%Y%m%d')
    datetime.datetime(2001, 12, 31, 0, 0)