Have you ever wondered how computers keep track of time? Almost all of them start counting according to the Unix epoch, dating from January 1st, 1970, at 00:00:00 UTC.
In programming, we need a way to work with and manipulate dates and times in a human-readable format. As with many other languages, Python has built-in support for such tasks, via the
datetime module, containing a range of classes and functions that we may find useful.
We'll focus on providing a limited overview since dates and times in programming are quite a challenging and complex topic.
Getting the Current Date
By using the
datetime class, we can get the current date in a specific format, and use it to tackle the most common, recurring task when working with dates.
from datetime import datetime current_date = datetime.now() print("The current date is", current_date)
If we run this in the console, the output will contain the current date and time, in the format
YYYY-MM-DD HH:MM:SS.ssssss, where
YYYY is the year,
MM is the month,
DD is the day,
HH is the hour,
MM is the minute,
SS is the second, and
ssssss is the microsecond.
Working with Date Components
Logically, we can also extract specific components that we may need by using additional methods from the module, like so:
year: Returns the year of the date.
month: Returns the month of the date.
day: Returns the day of the month of the date.
hour: Returns the hour of the date.
minute: Returns the minute of the date.
second: Returns the second of the date.
from datetime import datetime current_date = datetime.now() print("Year:", current_date.year) print("Month:", current_date.month) print("Day:", current_date.day) print("Hour:", current_date.hour) print("Minute:", current_date.minute) print("Second:", current_date.second)
We can also create our own date objects using the datetime class constructor.
from datetime import datetime date_object = datetime(2022, 12, 25, 12, 0, 0) print("Date Object:", date_object) # Output: 2022-12-25 12:00:00.
Formatting Date Objects
In many cases, we may want to format a date object into a human-readable string. We can do this by leveraging the
strftime method of the
datetime class. Moreover, the
strftime method takes one parameter,
format, which we use to specify the format of the returned string.
from datetime import datetime date_object = datetime(2023, 3, 1, 12, 0, 0) formatted_date = date_object.strftime("%B %d, %Y") print("Formatted Date:", formatted_date) # Output: Formatted Date: March 01, 2023
Let's also explain the symbol usage. The
%B format specifier represents the full month name, while
%d represents the day of the month as a zero-padded decimal number, and lastly,
%Y represents the year with century as a decimal number.
Date Class Methods
As always, for clarity purposes, you can find a comprehensive table of some useful methods from the
|strftime(format)||Formats the date object into a string using the specified format.|
|replace(year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=None)||Returns a new |
|astimezone(tz)||Converts the |
|date()||Returns the date part of the |
|time()||Returns the time part of the |
|timestamp()||Returns the timestamp of the |
|weekday()||Returns the day of the week as an integer, where Monday is 0 and Sunday is 6.|
|isoweekday()||Returns the ISO day of the week as an integer, where Monday is 1 and Sunday is 7.|
|isoformat()||Returns the string representation of the date in the ISO format |
|ctime()||Returns the string representation of the date in the format |
|fromisocalendar()||Returns a date corresponding to the ISO calendar.|
|fromisoformat()||Returns a date object from the string representation of the date.|
|fromordinal()||Returns a date object from the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1.|
|fromtimestamp()||Returns a date object from the POSIX timestamp.|
|isocalendar()||Returns a tuple year, week, and weekday.|
|toordinal()||Returns the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1.|
|timetuple()||Returns an object of type time.struct_time.|
|today()||Returns the current local date.|
Handling Time Zones
The most challenging factors of working with dates usually include time zones, daylight saving time, and leap years. As with many other concepts in programming, it's quite common to rely on a third-party solution that even the official documentation of the language supports.
dateutil module is a prime example of that, providing us support for parsing dates and a variety of formats for flexible handling of time zones, as well as handling daylight saving time automatically.
A similar library to
pytz. Bear in mind, that its interface is slightly different than
datetime.tzinfo so there are some caveats involved. If you plan on using it, make sure to read about it in the additional resources. You can also find other worthy mentions such as
Arrow, which is inspired by
Moment.js, or data science relates ones such as
Pandas, each equipped with different tooling.
As a beginner, it's crucial to familiarize yourself with the various methods and functions provided by the built-in modules. Furthermore, one should experiment with different third-party solutions to get a feel of how they work and extend the built-in ones. Lastly, we strongly recommend that you check out some of the additional resources below, to understand the challenges of working with dates.