![]() |
VOOZH | about |
Python provides tools for managing date and time using the datetime module. Whether you're fetching the current time, formatting it, handling timezones or calculating time differences, this module makes it simple. For example, you can easily convert "2001-11-15 01:20:25" from Asia/Kolkata to America/New_York or add 90 days to the current time using a timedelta.
Let’s go through the most useful operations when working with datetime and timezones.
A very easy way to get a Datetime object is to use the datetime.now() method. A DateTime object is an instance/object of the datetime.datetime class. The now() method returns an object that represents the current date and time.
2025-06-17 12:32:58.612718
Explanation:
We can also declare the DateTime object manually
2001-12-09 00:00:00
Explanation:
After this, we learn how to format our Datetime objects.
For printing our datetime objects in different formats, we use strftime() method. The syntax of strftime() is:
strftime(format)
Sun 12 01 12-09-2001 00:00:00:00AM
Explanation:
We can get different attributes of the datetime object. In the code below, we are going to get the hours, minutes, and seconds.
12 11 23
Explanation: You can access time components directly using attributes like .hour, .minute, and .second.
We can also get a datetime object using the strptime() method, in which we get a DateTime object from a string. Since the strings we use can be formatted in any form, we need to specify the expected format. To understand this, let's look at the syntax of strptime():
datetime.strptime(data,expected_format)
Parameters :
2013-01-01 12:30:00
Explanation:
The DateTime objects that we have been working with till now are what are known as naive DateTime objects. A naive DateTime object does not have any information on the timezone. We can check this using the tzinfo property.
None
Explanation:
To set our own timezones, we have to start using the pytz module. In the next example, we will create a DateTime object first and then create a timezone object. We will then localize that timezone object to the DateTime object and check the tzinfo property.
Asia/Kolkata
Explanation:
To convert the DateTime object from one timezone to another we need to use the astimezone() method.
DateTimeObject.astimezone(tz=None)
where:
returns: a datetime instance according to the specified time zone parameter tz
2001-11-14 14:50:25-05:00
Explanation: