CodeGym /Courses /Python SELF EN /Working with Date and Time Basics in Python

Working with Date and Time Basics in Python

Python SELF EN
Level 39 , Lesson 0
Available

Introduction to Working with Date and Time

Let’s start with a little thought: imagine if computers couldn’t work with date and time. Yikes! Our beloved gadgets would become completely useless for planning and automating tasks. Let's figure out how Python helps us not to be late for important meetings and keeps automation of routine tasks running.

Working with date and time is an integral part of programming, especially when it comes to automation. Imagine this: you have reports that need to be updated every hour or reminders that should remind you that it's time for a break (yes, because you’ve been glued to your monitor for 5 hours now!). Python offers lots of tools for working with date and time, which we’ll dive into in this lecture.

1. Modules for Working with Date and Time

Python comes with several modules that make working with date and time easier. We'll focus on three main modules: datetime, time, and calendar.

  • datetime: Probably most of the heavy lifting with date and time will be done using this one. It provides classes to work with individual dates, times, and their combinations.
  • time: This module provides functions for dealing with low-level time representations, often interacting with system time.
  • calendar: It helps you work with calendars (pretty self-explanatory).

Main Functions and Classes of the datetime Module

Let’s dive deeper into the datetime module and take a look at its key components.

The date Class

This class is for working with dates. It allows you to set and modify years, months, and days without needing to tie them to a time.

Python

from datetime import date

# Creating a date object
my_birthday = date(1990, 12, 25)
print("The date of my birthday:", my_birthday)

The time Class

This class, as the name suggests, is exclusively about time — hours, minutes, seconds. Perfect for cases when you need to handle time separately from the date.

Python

from datetime import time

# Creating a time object
meeting_time = time(14, 30)  # 2:30 PM
print("Meeting time is set to:", meeting_time)

The datetime Class

The most versatile class, combining date and time into one.

Python

from datetime import datetime

# Current date and time
now = datetime.now()
print("Current date and time:", now)

2. Using the datetime Module to Get the Current Date and Time

Getting the current date and time is fundamental for planning and automation. The datetime module has several convenient methods to do that.

Getting the Current Date and Time

With the datetime.now() and datetime.today() methods, you can easily get the current date and time.

Python

now = datetime.now()
print("Current date and time (now):", now)

today = datetime.today()
print("Current date (today):", today)

Working with datetime Objects

The datetime object allows you to extract time components like year, month, day, and more. It’s also important to keep in mind the differences between local and universal (UTC) time.

Python

year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second

print(f"Today is: {day}/{month}/{year}, and the time is: {hour}:{minute}:{second}")

When building apps, remember to consider the differences between local and UTC time, because the world is huge, and everyone’s on different clocks!

3. Real-Life Examples of Using the Current Date and Time

Let’s say you need to pull data from some source every hour. You can easily automate this by comparing the current time with the last extraction time. For example:

Python

from datetime import timedelta

last_run = datetime.now() - timedelta(hours=1)
current_time = datetime.now()

# If the last run was more than an hour ago
if current_time - last_run > timedelta(hours=1):
    print("Time to update the data!")
    last_run = current_time

This code effectively reminds us to do something only when more than an hour has passed. Notice how conveniently we use timedelta for math operations with time.

1
Task
Python SELF EN, level 39, lesson 0
Locked
Extracting the Current Date
Extracting the Current Date
2
Task
Python SELF EN, level 39, lesson 0
Locked
Time Difference
Time Difference
3
Task
Python SELF EN, level 39, lesson 0
Locked
Automatic Reminder
Automatic Reminder
4
Task
Python SELF EN, level 39, lesson 0
Locked
Scheduled Event Management
Scheduled Event Management
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION