- Introduction
- YouTube Video
-
Using The datetime Python Library
- Displaying The Current Date And Time
- Displaying The Current Date
- Displaying The Current Time
- Calculate The Difference Between Two Dates
- Calculate The Difference Between Two Times
- Calculate The Difference Between Two Dates And Times
- Converting Between Date Formats
- Working With Dates / Times In Different Timezones
- Conclusion
- References
Introduction
Working with dates and times is something that comes up frequently when building solutions with any programming language. Most languages, including Python, will have a library built-in that can be used to work with dates and time.
For Python, there is a built-in library called datetime
that can be used to simplify working with dates and time based data.
If you would like a copy of the code examples for this article, the files are available on my GitHub page.
YouTube Video
If you would prefer to watch a video of this article, there is a video available on YouTube below:
Using The datetime Python Library
As the datetime
library is built-into Python, there is nothing, other than Python, to install. Let us look at some examples of how to use the datetime
library.
Displaying The Current Date And Time
First, let's get the current date and time:
from datetime import date, datetime, time, timedelta
# --- Get the current date and time:
print(f"Date & Time: {datetime.now()}\n")
Output:
Date & Time: 2024-11-12 17:29:29.030497
Using datetime.now()
provides both the current date and time of the system it was run on.
By default, the date is formatted as year-month-day. This is known as the ISO 8601 standard date format.
Displaying The Current Date
Now let's get just the current date:
# --- Get just the current date:
print(f"Date: {datetime.now().date()}\n")
Output:
Date: 2024-11-12
The syntax is very much the same as getting the date and time but adding .date()
to the end will display only the date.
Displaying The Current Time
Next, let's get just the current time:
# --- Get just the current time:
print(f"Time: {datetime.now().time()}\n")
Output:
Time: 17:29:29.030522
This is basically the same as getting just the date but instead of adding .date()
to the end, adding .time()
returns just the time.
Calculate The Difference Between Two Dates
Working out the difference between two dates and / or times is something that is done frequently. First, let's look at an example of how to work out the time difference between two dates:
# --- Show the difference between two dates:
date_one = date(year=2024, month=11, day=7)
date_two = date(year=2023, month=11, day=6)
print(f"The first time difference is: {date_one - date_two}\n")
Output:
The first time difference is: 367 days, 0:00:00
For each of the two date variables, a date is specified using the datetime.date()
method, with a year, month and day specified for each.
From there, a simple subtraction of one from the other is performed to work out the difference. You can also use addition as well.
Calculate The Difference Between Two Times
Now, let's look at another example but instead of showing the difference between two dates, show the difference between two times:
# --- Show the difference between two times:
time_one = timedelta(hours = 15, minutes = 52)
time_two = timedelta(hours = 13, minutes = 58)
Output:
The second time difference is: 1:54:00
This is very similar to the previous date example but it uses timedelta()
to set the time. Using time()
is not an option as it doesn't allow for mathematical operations to be performed against it.
Calculate The Difference Between Two Dates And Times
To wrap up working out the differences between dates or times, let's take a look at an example of how to work out the difference between two dates and times:
# --- Show the difference between two dates and times:
date_time_one = datetime(year = 2023, month = 4, day = 22,
hour = 11, minute = 52, second = 25)
date_time_two = datetime(year = 2022, month = 3, day = 22,
hour = 13, minute = 58, second = 57)
print(f"The third time difference is: {date_time_one - date_time_two}\n")
Output:
The third time difference is: 395 days, 21:53:28
This method basically uses the same method as working out the difference between two dates or times with additional arguments being passed for the hours, minutes and seconds. Milliseconds can also be passed, if needed.
Converting Between Date Formats
Working with different formatted dates is another common occurrence. There are three main date formats that are typically used:
- Year, Month, Day (ISO standard, which is Python's default format)
- Day, Month, Year (European standard)
- Month, Day, Year (U.S.A standard)
Converting between these formats in Python is easy to do with the datetime
library. The following example will show how to convert from the ISO format to both the European and U.S.A standard formats:
# --- Convert to European and U.S.A based date formats (dd-mm-yyyy / mm-dd-yyyy):
current_date = datetime.now()
print(f"Default Date Format: {current_date.date()}")
print(f"Current Time: {current_date.strftime('%H:%M:%S')}\n")
print(f"U.S.A Date Format: {current_date.strftime('%m/%d/%Y')}")
print(f"U.K Date Format: {current_date.strftime('%d/%m/%Y')}\n")
Output:
Default Date Format: 2024-11-12
Current Time: 17:29:29
U.S Date Format: 11/12/2024
U.K Date Format: 12/11/2024
The above example sets the current_date
variable to the current date and time. That is then used to convert the date using the strftime()
method to the format that is required.
To explain what the %m/%d/%Y
and %d/%m/%Y
mean inside the strftime()
method:
-
%m
is the month as a number -
%d
is the day -
%Y
is the full year (2023 for example) -
/
is used as the separator. It can be anything but it is best to use/
or a-
If the month needs to be the full name, rather than a number, change it from %m
to %B
.
The date would then be 22/April/2023
or April/22/2023
. This output format doesn't look ideal so change the output format to %d %B, %Y
(22 April, 2023
) or %B %d, %Y
(April 22, 2023
), both of which are more standard formats.
As for the Current time shown:
-
%H
is for the hours -
%M
is for the minutes -
%S
is for the seconds -
:
is the separator
Working With Dates / Times In Different Timezones
Last but not least, let's take a quick look at working with different timezones.
Now, up until Python 3.9, I typically would have used the third-party library called pytz but as of Python 3.9, is has pretty much been deprecated. The reason is that there is now a library in the standard Python library collection called zoneinfo
that does most of what pytz provided.
Let's take a look at some examples.
First, let's see what timezones are available in the zoneinfo
library:
# --- Import the required libraries / modules:
from datetime import datetime
from zoneinfo import available_timezones, ZoneInfo
# --- Show all of the available timezones:
print(available_timezones())
The output is far too long to show but all of the options in the (Python) set it produces can be used to take a date and time and convert it to the appropriate timezone. It won't however though convert the date format to the region of that timezone so that will need to be done manually, if required.
If you would like to see the list of timezones in a spreadsheet, there is one in the GitHub repository I linked at the beginning of this article.
First, define a format for the output of the date, time and timezone to be in and show an example:
# --- Set the format for the date, time and timezone to be shown:
datetime_format = '%d/%m/%Y, %H:%M:%S %Z (%z)'
# --- Get the local time (U.K in my case)
local_date_time = datetime.now()
# --- Display the local date, time and timezone:
print(f"Local Time: {local_date_time.strftime(datetime_format)}\n")
Output:
Local Time: 12/11/2024, 15:28:16 ()
A couple of points to observe here. First, in the datetime_format = '%d/%m/%Y, %H:%M:%S %Z (%z)'
variable, the %Z
indicates the name of the timezone to display and the %z
will display the time difference in hours.
Lastly, the Local Time
output has a set of parentheses (()
) at the end of it with nothing inside. The reason is because when datetime.now()
is used on its own, it doesn't include the timezone. To add the timezone to that, there are two ways to do it:
- Use
tz='name-of-timezone'
in the parentheses ofdatetime.now()
. For example:datetime.now(tz = ZoneInfo("Europe/London"))
. This would ensure that it works with the Europe/London timezone no matter what it is run on. - Alternatively, use
datetime.now().astimezone()
to use the current timezone of the system it is running on.
For example:
# --- Get the local time (U.K in my case)
# --- Method one, hard coding the timezone:
local_date_time = datetime.now(tz = ZoneInfo("Europe/London")) # not adding tz does not show timezone for uk
# --- Or
# --- Method two, getting the current timezone from the system:
local_date_time = datetime.now().astimezone() # This method gets the current system tz instead of hard coding as above
# --- Display the local date, time and timezone:
print(f"Local Time: {local_date_time.strftime(datetime_format)}\n")
Local Time: 12/11/2024, 15:28:16 ()
Local Time: 12/11/2024, 15:28:16 GMT (+0000)
Lastly, the following example will show a number of timezone conversions for different timezones in different regions / continents in the date format used in the U.K which will build on what has been done so far:
# --- List all of the timezones to use:
locations = [
{
"location": "Paris",
"timezone": "Europe/Paris"
},
{
"location": "Washington D.C",
"timezone": "US/Eastern"
},
{
"location": "Canberra",
"timezone": "Australia/Canberra"
}
]
# --- Display the local date, time and timezone:
print(f"Local Time: {local_date_time.strftime(datetime_format)}\n")
# --- Display the date, time and timezone from the list:
for location in locations:
print(f"{location['location']} Time: {local_date_time.astimezone(tz = ZoneInfo(location['timezone'])).strftime(datetime_format)}")
Output:
Local Time: 12/11/2024, 15:28:16 ()
Local Time: 12/11/2024, 15:28:16 GMT (+0000)
Paris Time: 12/11/2024, 16:28:16 CET (+0100)
Washington D.C Time: 12/11/2024, 10:28:16 EST (-0500)
Canberra Time: 13/11/2024, 02:28:16 AEDT (+1100)
There is also the option to use UTC time instead but that is out of the scope of this article.
Conclusion
Working with dates and times is something that is done a lot in Python (along with other languages). The examples shown are some of the most common tasks that I do the most often, outside of using Pandas.
There are many other options for working and manipulating date and time data so feel free to look at the documentation in the references section.
In closing, I hope this article was useful and have a nice day!
References
Documentation for the datetime library:
https://docs.python.org/3/library/datetime.html
Documentation for the timezone library:
Top comments (0)