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.
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.
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.
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.
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.
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:
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.
GO TO FULL VERSION