The Python DateTime module is perhaps one of the most frequently used and most important. The purpose of this quick guide is to show you the capabilities of this module through the use of simple code examples. The full length documentation of the Python DateTime module can be found HERE but our tutorial is more than enough to get you up and running quickly. ⚡⚡⚡
This code in this tutorial was written using Python 3.8.10.
Sections
Current Python DateTime & Timezones
Python DateTime Date Formats
Parsing Python DateTime
Python DateTime Date Arithmetic
Conclusion
Current Python DateTime & Timezones
from datetime import *
today = datetime.today()
now = datetime.now()
print(today)
#outputs: 2021-06-04 19:43:17.218465
print(now)
#outputs: 2021-06-04 19:43:17.218465
The first thing that we must do is actually import the datetime Python module, obviously😁. Then we create two variables and assign the current date and time using two different methods, today() and now() respectively. Both will give us the current date and time. The documentation states that now() is the preferred method because it is more precise. Also, now() takes an optional argument that allows us to get the current date and time in different time zone.
from datetime import *
from dateutil import tz
LA = tz.gettz('America/Los_Angeles')
now = datetime.now(LA)
print(now)
#outputs: 2021-06-04 17:16:39.215132-07:00
London = tz.gettz('Europe/London')
now = datetime.now(London)
print(now)
#outputs: 2021-06-05 01:16:39.215132+01:00
Paris = tz.gettz('Europe/Paris')
now = datetime.now(Paris)
print(now)
#outputs: 2021-06-05 02:16:39.217142+02:00
Mumbai = tz.gettz('Indian/Maldives')
now = datetime.now(Mumbai)
print(now)
#outputs: 2021-06-05 05:16:39.219110+05:00
Sydney = tz.gettz('Australia/Sydney')
now = datetime.now(Sydney)
print(now)
#outputs: 2021-06-05 10:16:39.219110+10:00
From the above snippet we see that, using now() (which returns a datetime object and NOT a string), we can get the time and date in several different time zones at once. But we also needed to import another library called dateutil (if you don’t have this, install at the terminal with the command: pip install python-dateutil) which will allow us to use the tz module and the gettz method to get the time at the specified timezone. We can get a full list of time zones HERE and documentation of dateutil HERE.
Note also the time zone is appended at the end of the datetime, for example +01:00 and +02:00. This is called the UTC Offset and is usually in the format ±hh:mm.
We can also print the current time zone that we are in with the following:
from dateutil.tz import *
from datetime import *
print(datetime.now(tzlocal()).tzname())
#outputs: SA Western Standard Time
In this instance, the call datetime.now(tzlocal()).tzname() gives us the current local Time Zone in the long name format. You can find a complete list of Time Zones with their long names HERE.
Finally we can define a simple date time using the Date
Python DateTime Date Formats
Formatting is critical. It is not enough to have the accurate date and time, but we must display it correctly according to project requirements.
from datetime import *
from dateutil import tz
LA = tz.gettz('America/Los_Angeles')
now = datetime.now(LA)
dto = datetime.strptime(str(now), '%Y-%m-%d %H:%M:%S.%f%z')
print('Date 1:', dto.strftime("%a %d %b %Y"))
# Date 1: Sat 05 Jun 2021
print('Date 2:', dto.strftime("%a %d %b %Y %H:%M:%S.%f"))
# Date 2: Sat 05 Jun 2021 03:27:38.897025
print('Date 3:', dto.strftime("%a %d %b %Y %I:%M:%S.%f %p"))
# Date 3: Sat 05 Jun 2021 03:27:38.897025 AM
print('Date 4:', dto.strftime("%a %d %b %Y %I:%M:%S.%f %p %z"))
# Date 4: Sat 05 Jun 2021 03:27:38.897025 AM -0700
print('Date 5:', dto.strftime("%a %d %b %Y %I:%M:%S.%f %p %Z"))
# Date 5: Sat 05 Jun 2021 03:27:38.897025 AM UTC-07:00
The above example gives several different ways to show the current date and time using python datetime. First we create a datetime object with strptime() and then we display it using strftime() in a specified format. In both cases we use format codes. These codes are critical if you want to customize the look of your dates in python. Below is a partial list, you can find the full list HERE, but below we have a partial list for your reference:
- %Y: Year (4 digits)
- %m: Month
- %z: UTC Offset
- %Z: Time zone name
- %d: Day of month
- %H: Hour (24 hour)
- %M: Minutes
- %S: Seconds
- %f: Microseconds
- %I: Hour 00-12
- %p: AM/PM
- %A: Weekday, full version
The above snippet can actually be accomplished with less code. The now variable is already a datetime object, there is no need to cast as a string to be passed to strptime(), we can use it immediately after getting the current datetime. See below:
from datetime import *
from dateutil import tz
LA = tz.gettz('America/Los_Angeles')
now = datetime.now(LA)
print(now.strftime("%a %d %b %Y %I:%M:%S.%f %p %Z"))
#outputs: Sat 05 Jun 2021 03:37:16.191346 AM PDT
Finally we can define a simple datetime object with datetime(year, month, day, hour=0, minute=0, second=0) or datetime.fromisoformat(). Consult the documentation for more info on these methods.
from datetime import *
print(datetime(2024, 7, 26, 12, 12, 12, 0))
print(datetime.fromisoformat('2024-07-26'))
print(datetime.fromisoformat('2024-07-26T12:12:24'))
print(datetime.fromisoformat('2024-07-26 12:59:23.283'))
print(datetime.fromisoformat('2024-07-26 12:59:22.222-07:00'))
#Outputs
#2024-07-26 12:12:12
#2024-07-26 00:00:00
#2024-07-26 12:12:24
#2024-07-26 12:59:23.283000
#2024-07-26 12:59:22.222000-07:00
Parsing Python DateTime
The dateutil library can also be used to parse strings and create datetime objects. When we are unsure of the date input, it would be wise to parse date time strings before they are used. Getting data from user input or external sources are good examples of times when we need to parse the dates.
from datetime import *
import dateutil.parser
inputDate = '13-12-2024'
parsedInputDate = dateutil.parser.parse(inputDate)
print(parsedInputDate.strftime("%a %d %b %Y %I:%M:%S.%f %p %Z"))
#outputs: Sun 13 Dec 2020 12:00:00.000000 AM
inputDate = '12-13-2024'
parsedInputDate = dateutil.parser.parse(inputDate)
print(parsedInputDate.strftime("%a %d %b %Y %I:%M:%S.%f %p %Z"))
#outputs: Sun 13 Dec 2020 12:00:00.000000 AM
Above we see two examples of parsing date string literals. The dateutil.parser.parse() method is smart enough to try to guess what specific date and time the string is trying to identify. If it can’t make a an approximate guess, it throws an error but as you will see in the below example, it is quite versatile which is why it should always be a part of your python datetime coding arsenal.
import datetime
import dateutil.parser
inputDate = '2024'
parsedInputDate = dateutil.parser.parse(inputDate)
print(parsedInputDate.strftime("%a %d %b %Y %I:%M:%S.%f %p %Z"))
#outputs: Wed 05 Jun 2024 12:00:00.000000 AM
inputDate = '12'
parsedInputDate = dateutil.parser.parse(inputDate)
print(parsedInputDate.strftime("%a %d %b %Y %I:%M:%S.%f %p %Z"))
#outputs: Sat 12 Jun 2021 12:00:00.000000 AM
As you saw above, even if you don’t supply every part of the date, the dateutil.parse.parse() method will make a pretty good guess as to what is intended. It is still your duty to make sure that datetime values are accurate by how you handle these eventualities in your code.
There is actually something else here. Did you notice that the %Z format code did NOT produce any output in the above examples? This is because our parsed date time by default isn’t time zone aware. We can fix this with the following code:
from datetime import *
import dateutil.parser
from pytz import timezone
import pytz
inputDate = '7-26-2024'
parsedInputDate = dateutil.parser.parse(inputDate)
eastern = timezone('US/Eastern')
parsedInputDatetz=eastern.localize(parsedInputDate)
print(parsedInputDatetz .strftime("%a %d %b %Y %I:%M:%S.%f %p %Z"))
#outputs: Fri 26 Jul 2024 12:00:00.000000 AM EDT
print(parsedInputDatetz .strftime("%a %d %b %Y %I:%M:%S.%f %p %z"))
#outputs: Fri 26 Jul 2024 12:00:00.000000 AM -0400
Here we introduce the pytz library which we can use to make our parsed date string ‘time zone aware’. You can install it with the command pip install pytz at the command line if you don’t already have it. Find more info HERE. You will notice that this time both the %Z and %z time codes allow us to see the time zone, both UTC Offset and the Time Zone name. Find out more about the amazing functionality of pytz HERE.
Python DateTime Date Arithmetic
The Python DateTime library also allows us to quickly do date and time arithmetic. We can add or subtract anything from weeks to microseconds. Anything larger than a week will have to be converted into weeks (1 year = 52 weeks) and supplied as a parameter.
from datetime import *
print(datetime.now() + timedelta(days=70))
#2021-08-14 08:10:19.919848
print(datetime.now() - timedelta(days=70))
#2021-03-27 08:10:19.920349
print(datetime.now() + timedelta(hours=700))
#2021-07-04 12:10:19.921305
print(datetime.now() - timedelta(hours=700))
#2021-05-07 04:10:19.921779
print(datetime.now() + timedelta(seconds=70))
#2021-06-05 08:11:29.922482
print(datetime.now() - timedelta(seconds=70))
#2021-06-05 08:09:09.922482
print(datetime.now() + timedelta(weeks=58800))
#3148-05-08 08:10:19.922482
print(datetime.now() - timedelta(weeks=58800))
#0894-07-03 08:10:19.923483
As we can see, basic arithmetic is easily accomplished with the timedelta() method. The full documentation can be found HERE.
Conclusion
The purpose of this guide was to get you started. Your projects may certainly have other requirements but this guide will certainly be enough to get you started along with the formal documentation. Python DateTime is going to be a library that you use often in your Python journey.
There are other ways you can find the time in other time zones. Click HERE to check out the article. Good luck! 👌👌👌