Explain Codes LogoExplain Codes Logo

How do I convert a datetime to date?

python
datetime
date
timezone
Nikita BarsukovbyNikita Barsukov·Feb 11, 2025
TLDR

To convert a datetime object to a date object in Python, use the datetime_object.date() function.

from datetime import datetime # Jedi slicing technique to save only the date date_only = datetime.now().date()

This function effectively discards the time portion of a datetime object, returning a date object.

Time zone tango

Converting a datetime object to a date object might need you to waltz with time zones. Use pytz or the timezone module from datetime to perform a time zone-aware conversion.

from datetime import datetime, timezone import pytz # As wise Yoda said, be aware of the time zone, you must 👀 datetime_obj = datetime.now(pytz.utc) date_only = datetime_obj.astimezone(timezone.utc).date()

Python version party

Mind you, the Python version you are using might affect datetime conversions. To prevent any party crashers, make sure to check the official Python documentation regarding datetime for your Python version.

Unwrapping today's date

Need just the date for today without the time? Use:

from datetime import datetime, date # Present unwrapping time 🎁 today_date = datetime.now().date() # Local date today_utc_date = datetime.utcnow().date() # Universal Time date today = date.today() # Another way to get today's date

Crafting custom formats with strftime

Need dates in strings with custom formats? That's what strftime is for:

from datetime import datetime # Tailoring the date to your needs 💇‍♀️ formatted_date = datetime.now().strftime('%Y-%m-%d')

Time-traveling pitfalls to avoid

Don't get fooled by datetime.today().time() believing it'd give you a date. It's a sneaky function that fetches you the current time, not a stripped down date object.

Practical examples and nuggets of wisdom

Juggling with time zones

Here's how to transform time zones to ensure accuracy before getting the date:

from datetime import datetime import pytz # East? I thought you said Weast! 🧭 eastern = pytz.timezone('US/Eastern') datetime_obj = datetime.now(eastern) date_obj_utc = datetime_obj.astimezone(pytz.utc).date()

Incrementing and comparing dates

date objects play nice with comparison, and they handle increments like a boss:

from datetime import timedelta, datetime # Let's play 'Which date is bigger?' 🃏 date1 = datetime.now().date() date2 = (datetime.now() + timedelta(days=1)).date() print(date1 < date2) # True: date1 is earlier than date2 # Tomorrow: just one timedelta away! ➡️ date_tomorrow = date1 + timedelta(days=1)

Dealing with pandas Timestamp

Pandas Timestamp gives you dates, not cute animal timestamps 😉

import pandas as pd # No, pandas can't timestamp... yet 🐼 timestamp = pd.Timestamp('2023-04-15 13:45:32') date_only = timestamp.date()