Logo
Unit 13 – Python Standard Library: Datetime and Time

Python Standard Library: Datetime and Time

Duration: 5 minutes

Python’s standard library includes numerous modules for handling dates and times. Today, we’ll concentrate on two of them: **‘datetime’ **and ‘time’.

The datetime Module

The **datetime** module supplies classes for manipulating dates and times. Here are a few important classes:- ** datetime. date:** An idealized naive date, assuming the Gregorian calendar.

  • ** datetime. time**: An idealized time, independent of any particular day.
  •  datetime. datetime: A combination of a date and a time.
Here's an example of using the `datetime` module:
from datetime import datetime, date, time
# Get the current date
today = date. today()
print(f"Today's date is {today}")
# Get the current time
now = datetime. now(). time()
print(f"Current time is {now}")
# Get the current date and time
now_full = datetime. now()
print(f"Current date and time is {now_full}")

The time Module

The **time** module provides various time-related functions. It’s useful when you want to record the time of events, measure time, or implement features that need to wait or pause:

import time
# Get the time since epoch
seconds = time. time()
print(f"Seconds since epoch={seconds}")
# Convert the time in seconds since the epoch to a string
time_string = time. ctime(seconds)
print(f"Time string is {time_string}")

Exercise

Now create a Python script that uses both the **‘datetime’ **and **‘time’ **modules. The script should display the current date and time, as well as the time in seconds since the epoch (also known as Unix or POSIX time).

Conclusion

The ‘datetime’ and ‘time’ modules in Python provide extensive capabilities for working with dates, times, and durations. These modules have you covered whether you’re scheduling events, timestamping logs, or measuring performance! Keep up the good work!

Next Tutorial: Python Standard Library: Math and Random

5 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!