24. Python Dates and Time
Python Dates and Time
A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects. Handling dates and times is notoriously tricky in programming due to timezones, leap years, and formatting differences across regions. Python's datetime module abstracts this complexity away.
Getting the Current Date and Time
To get the current exact moment in time, use the now() method from the datetime class inside the datetime module.
The date contains year, month, day, hour, minute, second, and microsecond.
Creating a Custom Date Object
To create a specific date, you can use the datetime() constructor class. It requires three mandatory integer parameters: year, month, day. You can optionally pass hours, minutes, seconds, and microseconds (which default to 0).
Extracting Date Components
Once you have a datetime object, you can easily extract specific pieces of information from it using its properties.
The strftime() Method (Formatting Dates)
The strftime() method takes a datetime object and formats it into a human-readable string based on a format code. This is how you change "2026-05-22" into "May 22, 2026".
There are many format codes. For example: %m (Month as a number 01-12), %H (Hour 00-23), %M (Minute 00-59).
The strptime() Method (Parsing Strings to Dates)
Often, you will receive a date as a text string (e.g., from a CSV file or an API) and need to convert it into a true datetime object. You do this using strptime() (string parse time). You must tell Python the exact format the string is currently in.
Time Math with timedelta
You cannot simply add an integer like `+ 5` to a date object to jump forward 5 days. Instead, you use the timedelta object, which represents a duration of time.
Knowledge Check
Ready to test your understanding of 24. Python Dates and Time?