CodeGym /Courses /Python SELF EN /Working with the datetime Module

Working with the datetime Module

Python SELF EN
Level 39 , Lesson 1
Available

1. Getting the Current Date and Time

Why do we need it?

As they say, time is money. And in programming, it’s also about control, planning, and automation. For example, if you want to run a task at a certain time or log some events, you need to know that the clock is ticking and how to interact with it.

Basics of datetime

Alright, let’s assume we’ve just started working with the datetime library. Unlike building a spaceship, this is super simple! Let’s start by grabbing the current date and time:

Python

from datetime import datetime

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

This code is like saying, "Hey, datetime, let’s find out what time it is now!" And what’s cool is that now() returns a datetime object that holds all the info about the current moment. Yep, just like a professor who knows everything all at once.

Local and Universal (UTC) Time

Ah, UTC—the universal time that connects all of us without worrying about time zones. If you want to know the exact time on Mars (well, almost), UTC is your guy. Here’s how to get it:

Python

# Getting the current time in UTC format
now_utc = datetime.utcnow()
print("Current date and time in UTC:", now_utc)

You might ask, what’s the difference? Local time considers your time zone, while UTC is Greenwich Mean Time, independent of geographical location.

Extracting Date and Time Components

Sometimes we don’t need the whole date, but just a part of it. It’s like ordering pizza and taking only the cheese—not always logical, but sometimes necessary:

Python

# Extracting individual parts of date and time
year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second

print(f"Now it's {hour}:{minute}:{second} {day}.{month}.{year}")

This way, we can individually work with date and time components, for example, to wish a colleague happy birthday (but only if they remind us).

Examples of Using the Current Date and Time

Another case is when you need to code events happening at different times. For example, let’s create the simplest script that congratulates everyone on Friday (because who doesn’t love Friday?).

Python

# Example of using the current date for a daily reminder
if now.weekday() == 4:  # Friday
    print("Woohoo! It's Friday, time to relax!")
else:
    print("Hang in there, Friday isn’t here yet.")

This code uses the weekday() method, which returns a number from 0 to 6 (where 0 is Monday, and 6 is Sunday), to check what day of the week it is and prepare for the approaching weekend Viking.

2. Working with datetime Objects

We need to know not only the moment we’re in but also how to transition between moments for operations or comparisons. For example, how do you calculate how late you are for a meeting with colleagues?

Python

# Example of calculating time differences
from datetime import timedelta

# Creating a past date
past_date = datetime(2023, 1, 1, 10, 0, 0)

# Calculating the difference between the current time and the past
difference = now - past_date
print(f"{difference.days} days and {difference.seconds // 3600} hours have passed since that memorable day.")

Here we create a past date and compare it with the present. How many days have passed since New Year’s? Now you know!

3. Working with Time Zones

For working with time zones in datetime, we use the pytz library, which allows us to convert date and time to the desired time zone.

Example of Using pytz

Python

from datetime import datetime
import pytz

# Getting the current date and time in UTC
utc_now = datetime.now(pytz.utc)
print("Current date and time (UTC):", utc_now)

# Converting to another time zone (e.g., US/Pacific)
pacific_now = utc_now.astimezone(pytz.timezone("US/Pacific"))
print("Current date and time (Pacific Time):", pacific_now)

Output:


Current date and time (UTC): 2024-11-04 14:53:27.123456+00:00
Current date and time (Pacific Time): 2024-11-04 06:53:27.123456-08:00
1
Task
Python SELF EN, level 39, lesson 1
Locked
Getting the current date and time
Getting the current date and time
2
Task
Python SELF EN, level 39, lesson 1
Locked
Difference between dates
Difference between dates
3
Task
Python SELF EN, level 39, lesson 1
Locked
Extracting Time Elements
Extracting Time Elements
4
Task
Python SELF EN, level 39, lesson 1
Locked
Time Conversion Across Different Time Zones
Time Conversion Across Different Time Zones
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION