Formatting and parsing dates
Dates often arrive as text from files or APIs and need to leave as text in reports. strftime turns a datetime into a formatted string. strptime goes the other way, turning a string into a datetime you can compute with.
Dates rarely live as Python objects on disk. They arrive as text from CSV files, APIs, and user input, and they often need to leave again as nicely formatted strings.
strftime turns a datetime into a string. strptime parses a string into a datetime. The two work with the same set of format codes.
Format a date with the ISO pattern %Y-%m-%d:
The format codes you will use most often:
What will be the output?
Mix codes with regular text to build human-friendly strings:
What will be the output?
strptime is the reverse. You hand it a string and the matching format pattern, and it returns a real datetime you can do math with.
Parse a date string into a datetime:
What will be the output?
The format string must match the input exactly, separators included. A wrong pattern raises ValueError. Note that strptime always returns a datetime, never a plain date.
Parse a date with time-of-day included:
What will be the output?
A common pattern is parsing strings into datetimes, doing some work, then formatting them back into strings for output.
What will be the output?
What will be the output?
What will be the output?