No Result
View All Result
DevRescue
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
DevRescue
Home Blog Python

Python DateTime Starter Guide

by Khaleel O.
June 5, 2021
in Python
Reading Time: 10 mins read
A A
Python DateTime
Python DateTime

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

BACK TO TOP

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

BACK TO TOP

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.

BACK TO TOP

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.

BACK TO TOP

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! 👌👌👌

Tags: datetimeformatted string in pythonpython datetime
Previous Post

Formatted String In Python 3

Next Post

Python Timezone List Tutorial

Khaleel O.

Khaleel O.

I love to share, educate and help developers. I have 14+ years experience in IT. Currently transitioning from Systems Administration to DevOps. Avid reader, intellectual and dreamer. Enter Freely, Go safely, And leave something of the happiness you bring.

Related Posts

Python

Python Fibonacci Recursive Solution

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Fibonacci Recursive Solution. Let's go! 🔥🔥🔥 The Fibonacci sequence is a series of numbers in which...

Read moreDetails
Python

Python Slice String List Tuple

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Slice string list tuple how-to tutorial. Let's go! 🔥🔥🔥 In Python, a slice is a feature...

Read moreDetails
Python

Python Blowfish Encryption Example

by Khaleel O.
January 14, 2024
0
0

Let's do a Python Blowfish Encryption example. Let's go! 🔥 🔥 Blowfish is a symmetric-key block cipher algorithm designed for...

Read moreDetails
Python

Python Deque Methods

by Khaleel O.
January 14, 2024
0
0

In this post we'll list Python Deque Methods. Ready? Let's go! 🔥🔥🔥 A deque (double-ended queue) in Python is a...

Read moreDetails

DevRescue © 2021 All Rights Reserved. Privacy Policy. Cookie Policy

Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
Manage options Manage services Manage {vendor_count} vendors Read more about these purposes
Manage options
{title} {title} {title}
Manage your privacy
To provide the best experiences, DevRescue.com will use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
Manage options Manage services Manage {vendor_count} vendors Read more about these purposes
Manage options
{title} {title} {title}
No Result
View All Result
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us

DevRescue © 2022 All Rights Reserved Privacy Policy