Python - Date and Time

Hello there, future Python wizards! Today, we're going to embark on an exciting journey through the realm of dates and times in Python. As your friendly neighborhood computer teacher, I'm thrilled to guide you through this adventure. So, grab your virtual wands (keyboards), and let's dive in!

Python - Date & Time

What are Tick Intervals?

Before we start juggling with dates and times, let's understand a fundamental concept: tick intervals. In the world of computers, time is often measured in ticks. But what exactly is a tick?

A tick is like the heartbeat of your computer. It's the smallest unit of time that your computer's clock can measure. In Python, we measure ticks as the number of seconds that have passed since January 1, 1970, at 00:00:00 UTC. This point in time is often referred to as the "epoch."

Let's see how we can get the current tick value:

import time

ticks = time.time()
print("Current tick value:", ticks)

If you run this code, you'll see a large number printed out. That's the number of seconds that have passed since the epoch. Pretty cool, right?

What is TimeTuple?

Now, let's talk about TimeTuple. It's not a new dance move (although it does sound like one!), but rather a way Python represents time.

A TimeTuple is a tuple containing 9 elements that represent different aspects of time:

Index Attribute Values
0 Year (e.g., 2023)
1 Month 1-12
2 Day 1-31
3 Hour 0-23
4 Minute 0-59
5 Second 0-61 (60 and 61 for leap seconds)
6 Weekday 0-6 (0 is Monday)
7 Day of Year 1-366
8 DST -1, 0, 1 (Daylight Savings Time flag)

Don't worry if this seems overwhelming. We'll use these elements throughout our lesson, and you'll become familiar with them in no time!

Getting the Current Time

Let's start with something simple: getting the current time. Python makes this incredibly easy with the time module:

import time

current_time = time.localtime()
print("Current time:", current_time)

When you run this, you'll see a TimeTuple printed out. Each number corresponds to an element in the table we just saw. For example, if you see time.struct_time(tm_year=2023, tm_mon=6, tm_mday=15, tm_hour=14, tm_min=30, tm_sec=0, tm_wday=3, tm_yday=166, tm_isdst=0), it means it's June 15, 2023, at 2:30 PM.

Getting the Formatted Time

While TimeTuples are useful for computers, they're not very human-friendly. Let's format our time in a way that's easier to read:

import time

formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print("Formatted time:", formatted_time)

This will print something like "2023-06-15 14:30:00". Much better, right? The %Y, %m, %d, etc., are format codes that tell Python how to arrange the time elements. It's like giving Python a template for how you want your time to look.

Getting the Calendar for a Month

Now, let's step it up a notch and print out an entire calendar for a month. We'll use the calendar module for this:

import calendar

year = 2023
month = 6

print(calendar.month(year, month))

This will print out a nicely formatted calendar for June 2023. It's like having a mini desk calendar right in your Python program!

The time Module

We've already used the time module a bit, but let's explore it further. This module provides various time-related functions. Here are some useful ones:

import time

print("Current time in seconds since epoch:", time.time())
print("Current local time:", time.ctime())
print("Sleep for 2 seconds...")
time.sleep(2)
print("Woke up!")

The sleep() function is particularly useful when you want your program to pause for a bit. It's like telling your code to take a quick nap!

The calendar Module

We've seen how to print a month, but the calendar module can do much more:

import calendar

print("Is 2023 a leap year?", calendar.isleap(2023))
print("How many leap years between 2000 and 2050?", calendar.leapdays(2000, 2050))
print("What day of the week is 2023-06-15?", calendar.weekday(2023, 6, 15))

These functions help you work with calendars and dates easily. No more counting on your fingers to figure out leap years!

Python datetime Module

The datetime module is like the Swiss Army knife of time manipulation in Python. It combines the functionality of both time and calendar modules and adds even more features.

from datetime import datetime, date, time

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

# Creating a specific date
my_birthday = date(1990, 5, 15)
print("My birthday:", my_birthday)

# Creating a specific time
alarm = time(7, 30, 0)
print("Alarm set for:", alarm)

With datetime, you can create, manipulate, and format dates and times with ease.

Python date Object

The date object from the datetime module lets you work with dates (year, month, and day):

from datetime import date

today = date.today()
print("Today's date:", today)
print("Year:", today.year)
print("Month:", today.month)
print("Day:", today.day)

It's like having a smart calendar that knows what day it is and can tell you all about it!

Python time Object

Similarly, the time object lets you work with times (hour, minute, second, microsecond):

from datetime import time

lunch_time = time(12, 30, 0)
print("Lunch time:", lunch_time)
print("Hour:", lunch_time.hour)
print("Minute:", lunch_time.minute)
print("Second:", lunch_time.second)

Now you can precisely schedule your coding breaks!

Python datetime Object

The datetime object combines date and time, giving you full control over both:

from datetime import datetime

now = datetime.now()
print("Current date and time:", now)
print("Current year:", now.year)
print("Current month:", now.month)
print("Current day:", now.day)
print("Current hour:", now.hour)
print("Current minute:", now.minute)
print("Current second:", now.second)

It's like having a super-powered watch that knows everything about the current moment!

Python timedelta Object

Last but not least, let's talk about timedelta. This object represents a duration of time, and it's incredibly useful for date arithmetic:

from datetime import datetime, timedelta

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

# Add 1 day
tomorrow = now + timedelta(days=1)
print("This time tomorrow:", tomorrow)

# Subtract 1 week
last_week = now - timedelta(weeks=1)
print("This time last week:", last_week)

With timedelta, you can time travel in your code! Well, sort of. You can easily calculate future and past dates, which is super handy for many applications.

And there you have it, my young Pythonistas! We've journeyed through the fascinating world of dates and times in Python. Remember, practice makes perfect, so don't hesitate to experiment with these concepts. Before you know it, you'll be manipulating time like a true coding time lord!

Credits: Image by storyset