How do I turn a Python datetime into a string, with readable format date?
Quickly turn a datetime
into a human-readable string using strftime
with a format like "%Y-%m-%d %H:%M:%S"
:
Modify the format string to your preference.
Detailed walkthrough
Extracting atomic date components
Did you know that datetime
objects are as sliceable as hot birthday cakes? Use dot notation to serve up the year, month, day, hour, minute, or second:
Date formatting with strftime
strftime
is your Pythonic date formatter. It uses format codes you can cherry-pick from the official Python docs (reference 1). Want a full-length month in your date or to add a comma? Use "%B %d, %Y"
:
F-strings for concise date formatting
Python 3.6+ users, meet f-strings. These guys will let you embed any expression, including datetime
objects, inside string literals:
This mint example showcases the martini-dry syntax of f-strings for in-line date formatting.
Alternative methods and best practices
Quick and dirty ctime formatting
For something fast with no frills, the ctime()
method of datetime
objects will kick out a readable timestamp.
While not customizable, it's a life-saver when you just need the timestamp in a jiffy.
The strftime Vs format() duel
Faced with the strftime
Vs format()
question? It's really all about the application and requirements of your code. If you're already formatting multiple variables into a string, hold onto your seat:
Warning: strftime arguments needed
When using strftime()
, never forget a piece of the format or you'll end up with strings missing parts or even errors. Always ensure your format codes yield the desired output:
Roadblocks and power tools
Time zone considerations
When you bring up time zones, make sure your datetime
object is timezone aware. Use %z
in strftime for this:
Localized date formatting
Need date names in a different language? Change the Python locale accordingly, but ensure it's supported by your system.
Complex date formatting with external libraries
When it comes to the bigger beasts of date formatting, Arrow or dateutil libraries (reference 6 & 7) got you covered. They bring new tools for date manipulation and formatting:
Was this article helpful?