How to Determine Time in Python

Have you ever wondered how to determine time in Python? Python provides a built-in module called datetime that enables us to work with dates and times easily. In this article, we will discuss how to determine time in Python using the datetime module. So, let’s get started.

Table of Contents

What is datetime module?

The datetime module supplies classes for working with dates and times. It provides various classes like date, time, datetime, timedelta, and tzinfo that help us to perform various operations related to dates and times.

The datetime module also provides various methods to format and print dates and times in different formats. It supports various date and time formats like ISO, RFC, and UNIX Timestamp.

Determining current time in Python

To determine the current time in Python, we can use the datetime module’s datetime class. The datetime class provides a method called now() which returns the current date and time.

import datetime

current_time = datetime.datetime.now()

print("Current Time is:", current_time)

Output:

Current Time is: 2021-08-11 08:59:54.778371

In the above code, we have imported the datetime module and used the datetime class to determine the current time. The now() method returns the current date and time, and we have stored it in the current_time variable. Finally, we have printed the current time using the print() function.

Determining current date in Python

To determine the current date in Python, we can use the datetime module’s date class. The date class provides a method called today() which returns the current date.

import datetime

current_date = datetime.date.today()

print("Current Date is:", current_date)

Output:

Current Date is: 2021-08-11

In the above code, we have used the date class to determine the current date using the today() method. We have stored the current date in the current_date variable and printed it using the print() function.

Formatting date and time in Python

The datetime module provides various methods to format dates and times in different formats. We can use the strftime() method to format dates and times in different formats.

import datetime

current_time = datetime.datetime.now()

formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")

print("Formatted Time is:", formatted_time)

Output:

Formatted Time is: 2021-08-11 09:17:20

In the above code, we have used the strftime() method to format the current time in the "Year-Month-Day Hour:Minute:Second" format. The strftime() method takes a format string as an argument, and we have passed the format string "%Y-%m-%d %H:%M:%S" to format the time.

Adding and subtracting time in Python

We can add or subtract time in Python using the timedelta class provided by the datetime module. The timedelta class represents a duration, and we can use it to perform various time-related operations.

import datetime

current_time = datetime.datetime.now()

print("Current Time is:", current_time)

# adding 1 day to current time
new_time = current_time + datetime.timedelta(days=1)

print("New Time is:", new_time)

# subtracting 1 day from current time
old_time = current_time - datetime.timedelta(days=1)

print("Old Time is:", old_time)

Output:

Current Time is: 2021-08-11 09:36:47.579697
New Time is: 2021-08-12 09:36:47.579697
Old Time is: 2021-08-10 09:36:47.579697

In the above code, we have used the datetime class to determine the current time. We have added one day to the current time using the timedelta(days=1) method and stored it in the new_time variable. Similarly, we have subtracted one day from the current time using the timedelta(days=1) method and stored it in the old_time variable.

Converting string to datetime in Python

We can convert a string to datetime in Python using the strptime() method provided by the datetime module. The strptime() method parses a string and returns a datetime object.

import datetime

date_string = "2021-08-11 09:50:00"
date_time = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")

print("Date Time Object is:", date_time)

Output:

Date Time Object is: 2021-08-11 09:50:00

In the above code, we have used the strptime() method to parse the string "2021-08-11 09:50:00" and convert it into a datetime object. We have passed the format string "%Y-%m-%d %H:%M:%S" to the strptime() method to specify the format of the string.

Converting datetime to string in Python

We can convert a datetime object to a string in Python using the strftime() method provided by the datetime module. The strftime() method formats a datetime object as a string.

import datetime

current_time = datetime.datetime.now()

formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")

print("Formatted Time is:", formatted_time)

Output:

Formatted Time is: 2021-08-11 10:06:51

In the above code, we have used the strftime() method to format the current time as a string in the "Year-Month-Day Hour:Minute:Second" format.

Time zone handling in Python

Python provides a module called pytz that enables us to work with time zones. The pytz module provides various time zones, and we can use them to perform various operations related to time zones.

import datetime
import pytz

timezone = pytz.timezone('US/Pacific')
current_time = datetime.datetime.now(timezone)

print("Current Time in US/Pacific is:", current_time)

Output:

Current Time in US/Pacific is: 2021-08-10 19:24:01.644836-07:00

In the above code, we have imported the pytz module and used the timezone() method to create a time zone object for the US/Pacific time zone. We have passed the time zone object to the now() method of the datetime class to determine the current time in the US/Pacific time zone.

Handling time intervals in Python

We can handle time intervals in Python using the datetime and timedelta classes provided by the datetime module. We can subtract two datetime objects to get a timedelta object, which represents the duration between two datetime objects.

import datetime

start_time = datetime.datetime.strptime("2021-08-11 10:30:00", "%Y-%m-%d %H:%M:%S")
end_time = datetime.datetime.strptime("2021-08-11 11:00:00", "%Y-%m-%d %H:%M:%S")

duration = end_time - start_time

print("Duration is:", duration)

Output:

Duration is: 0:30:00

In the above code, we have used the strptime() method to parse two strings and convert them into datetime objects. We have subtracted the start time from the end time to get the duration between the two times.

Working with epoch time in Python

Epoch time is the number of seconds that have elapsed since 00:00:00 UTC on January 1, 1970. We can work with epoch time in Python using the time module.

import time

current_time = time.time()

print("Current Epoch Time is:", current_time)

Output:

Current Epoch Time is: 1628686696.0143056

In the above code, we have used the time() method of the time module to determine the current epoch time.

Conclusion

In this article, we have discussed various operations related to time in Python using the datetime module. We have discussed how to determine the current time and date, format and print dates and times, add and subtract time, convert strings to datetime and datetime to strings, handle time zones, handle time intervals, and work with epoch time. I hope this article will help you in your Python programming journey.

Leave a Comment

Your email address will not be published. Required fields are marked *