How do I convert a datetime to date?
To convert a datetime
object to a date
object in Python, use the datetime_object.date()
function.
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.
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:
Crafting custom formats with strftime
Need dates in strings
with custom formats? That's what strftime
is for:
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:
Incrementing and comparing dates
date
objects play nice with comparison, and they handle increments like a boss:
Dealing with pandas Timestamp
Pandas Timestamp gives you dates, not cute animal timestamps 😉
Was this article helpful?