This blog talks about converting datetime between string and datetime with python. The principal python package we will use is datetime and dateutil.
Converting between datetime and string is a subject that we usually need to
handle during data processing. In this blog, I’ll talk about how to convert
datetime to string and inverse, with following date format:
YYYY-MM-DD
YY-MM-DD
MM-DD-YYYY
MM-DD-YY
DD-MM-YYYY
DD-MM-YY
YYYY/MM/DD
YY/MM/DD
MM/DD/YYYY
MM/DD/YY
DD/MM/YYYY
DD/MM/YY
Human-intelligible date
Converting from datetime to string
YYYY-MM-DD
You can convert datetime objects and pandas Timestamp object to string with
str or the strftime method:
%Y means four-digit year, %m presents two-digit month, %d describes
two-digit day, %F is the shortcut for %Y-%m-%d.
YY-MM-DD
%y means two-digit year.
MM-DD-YYYY
MM-DD-YY
DD-MM-YYYY
DD-MM-YY
YYYY/MM/DD
YY/MM/DD
MM/DD/YYYY
MM/DD/YY
%D is the shortcut for %m/%d/%y.
DD/MM/YYYY
DD/MM/YY
Converting from string to datetime
YYYY-MM-DD
datetime.datetime.strptime is a good way to parse a date with a
known format. However, it can be a bit annoying to have to write a format
spec each time, especially for common date formats. In this case, you can use
the parser.parse method in the third-party dateutil package.
YY-MM-DD
MM-DD-YYYY
MM-DD-YY
DD-MM-YYYY
DD-MM-YY
YYYY/MM/DD
YY/MM/DD
MM/DD/YYYY
MM/DD/YY
DD/MM/YYYY
DD/MM/YY
Human-intelligible date
Hope you like this blog and don’t hesitate if you want to ask a queston or
write a comment, it’s welcome!!
Reference
Wes McKinney. 2017. “Chapter 11 Time Series” Python for Data Analysis DATA
WRANGLING WITH PANDAS, NUMPY, AND IPYTHON p 319-323