Explain Codes LogoExplain Codes Logo

Convert datetime object to a String of date only in Python

python
datetime
date-formatting
f-strings
Alex KataevbyAlex Kataev·Jan 14, 2025
TLDR

To transform a datetime object into a string format displaying only the date, employ the strftime('%Y-%m-%d') method:

from datetime import datetime print(datetime.now().strftime('%Y-%m-%d')) # prints date as 'YYYY-MM-DD'

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:

from datetime import datetime print(datetime.now().strftime('%Y-%m-%d')) # 'I'm your yesterday's tomorrow!'

Slice and dice: Quick and clean

A method quicker than a ninja slicing through the night! Convert datetime to string and slice:

now = datetime.now() print(str(now)[:10]) # 'Split-second sushi chef'

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:

my_date = datetime.now() formatted_date = f"{my_date.year}-{my_date.month:02d}-{my_date.day:02d}" print(formatted_date) # 'Slithering through strings'

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:

date_to_convert = uncertain_datetime if date_to_convert: print(date_to_convert.strftime('%Y-%m-%d')) # 'Prepare before you dare'

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:

from datetime import datetime import pytz utc_now = datetime.now(pytz.utc) print(utc_now.strftime('%Y-%m-%d')) # 'Time Lord's order in chaos'

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.