Datetime Parsing and Formating¶
String to DateTime, strptime()¶
%I : 12-hour
%H : 24-hour
%M : Minute
%p : AM/PM
%y : 18
%Y : 2018
%b : Mar
%m : month (1 to 12)
%d : day
In [652]:
dt.datetime.strptime('9-01-18','%d-%m-%y')
Out[652]:
datetime.datetime(2018, 1, 9, 0, 0)
In [128]:
dt.datetime.strptime('09-Mar-2018','%d-%b-%Y')
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-128-09b44ac928e9> in <module>()
----> 1dt.datetime.strptime('09-Mar-2018','%d-%b-%Y')
AttributeError: 'datetime.timedelta' object has no attribute 'datetime'
In [129]:
datetime.datetime.strptime('2/5/2018 4:49 PM', '%m/%d/%Y %I:%M %p')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-129-201400445f8d> in <module>()
----> 1datetime.datetime.strptime('2/5/2018 4:49 PM', '%m/%d/%Y %I:%M %p')
NameError: name 'datetime' is not defined
Date/DateTime To String¶
str(), standard string format¶
In [130]:
str(dt.datetime.now())
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-130-6f15ba84cc1a> in <module>() ----> 1str(dt.datetime.now()) AttributeError: 'datetime.timedelta' object has no attribute 'datetime'
strftime(), custom string format¶
In [131]:
d = dt.datetime.now() dt.datetime.strftime(d, '%d-%b-%Y')
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-131-830f462914d5> in <module>() ----> 1d = dt.datetime.now() 2 dt.datetime.strftime(d, '%d-%b-%Y') AttributeError: 'datetime.timedelta' object has no attribute 'datetime'