Convert datetime object to a String of date only in Python
To transform a datetime object into a string format displaying only the date, employ the strftime('%Y-%m-%d') method:
Pick a method: strftime, slice, or f-string
strftime : The classic approach
The strftime method is the standard, flexible, and powerful way to format a datetime object:
Slice and dice: Quick and clean
A method quicker than a ninja slicing through the night! Convert datetime to string and slice:
Note: This method presumes your datetime string is in ISO format.
f-string : The Pythonista's choice
An f-string approach directly accesses the year, month, and day for formatting:
Combating common caveats
Fighting off None values
In the darker corners of your code, None values lurk. Check for None before calling methods to fend them off:
Creating custom formats and winning
strftime has a mini-language that allows for the creation of different date formats:
- %m/%d/%Y- U.S. date format
- %d-%m-%Y- European format
- %B %d, %Y- Verbose
Read the Python documentation to check out cool formatting tricks.
Controlling chaos: Time zones and UTC
To ensure consistency across different time zones, convert everything to UTC:
Code lessons for future you and your team
For readability and maintainability:
- Stick to one method of conversion throughout your code.
- Create a general function for conversions to keep things DRY.
- Add comments to denote the format and why a particular method was chosen.
To ace Python's date and time handling:
- Learn by doing. Write examples, mess around with different datetime objects and formats.
- Get official guidance from Python's datetime and pytz library documentation.
Was this article helpful?
