EASYTUTORGUIDE

Practical tutorials, tools, courses, digital skills, and business promotion.

Free Learning

JavaScript – Chapter 2: Development Environment

Learn what JavaScript is, where it runs, why it is important, and how beginners can start using it with simple examples and clear output.

Beginner Friendly JavaScript Basics Web Development Code Examples
JavaScript Lesson 2 Chapter 2 Topics Day / Night Mode

Main reading content

python-course-chapter-24

Chapter 24: Dates, Times, and Time Zones

A complete beginner-friendly guide to working with dates, times, time zones, timestamps, and scheduling in Python with practical explanations and examples.

Goal: Understand how to create, manipulate, format, parse, compare, calculate, and work with dates, times, time zones, and timestamps using Python's built-in date and time modules.

Chapter 24 Topics

24.1 Working with Dates

```

Dates are used in many computer programs. A school system may store a student's birth date, a store may record the date of a purchase, and a website may show when an article was published. Python provides special date objects that make it easier to store and work with dates correctly. A date usually contains a year, month, and day.

Using a date object is better than storing a date as ordinary text because Python can compare dates, calculate differences, and check whether a date is valid. For example, Python will not allow February 30 because that date does not exist. Date objects therefore reduce mistakes and make date-related programs easier to manage.

Example

# Import the date class from the datetime module
```

from datetime import date

# Create a date object

course_start = date(2026, 9, 8)

# Display the complete date

print(course_start)

# Display individual parts of the date

print("Year:", course_start.year)
print("Month:", course_start.month)
print("Day:", course_start.day)
```

Output

2026-09-08
```

Year: 2026
Month: 9
Day: 8
```

Output Explanation

The first output uses the standard year-month-day format. The next three lines display the year, month, and day separately. Python stores each part as a number, which makes it easy to use the values in calculations, comparisons, reports, and other program operations.

```

24.2 The datetime Module

```

Python's datetime module contains classes for working with dates and times. Important classes include date, time, datetime, timedelta, and timezone. Each class has a different purpose. The date class stores calendar dates, while the time class stores clock times.

The datetime class combines a date and a time in one object. The timedelta class represents a length of time, such as five days or two hours. You can import the entire module or import only the classes that your program needs.

Example

# Import the complete datetime module
```

import datetime

# Create a date object

today_date = datetime.date(2026, 7, 19)

# Create a time object

class_time = datetime.time(10, 30)

# Create a datetime object

class_meeting = datetime.datetime(2026, 7, 19, 10, 30)

print("Date:", today_date)
print("Time:", class_time)
print("Meeting:", class_meeting)
```

Output

Date: 2026-07-19
```

Time: 10:30:00
Meeting: 2026-07-19 10:30:00
```

Output Explanation

The date object displays only the calendar date. The time object displays the hour, minute, and seconds. The datetime object combines both values. Because the entire module was imported, each class name begins with datetime..

```

24.3 Current Date and Time

```

Many programs need to know the current date or current time. Python can retrieve this information from the operating system. The date.today() method returns the current local date, while datetime.now() returns the current local date and time together.

Current date and time values are useful for recording login times, creating file names, adding timestamps to reports, tracking orders, and showing when information was updated. The exact output changes depending on when and where the program is run.

Example

# Import the required classes
```

from datetime import date, datetime

# Get the current local date

current_date = date.today()

# Get the current local date and time

current_datetime = datetime.now()

print("Current date:", current_date)
print("Current date and time:", current_datetime)
```

Example Output

Current date: 2026-07-19
```

Current date and time: 2026-07-19 11:45:32.481920
```

Output Explanation

The first line displays the current date. The second line includes the date, hour, minute, second, and microseconds. Your output will be different because Python reads the current date and time from your own computer when the program runs.

```

24.4 Creating Date Objects

```

A date object is created by providing a year, month, and day to the date class. The values must form a real calendar date. The month must be between 1 and 12, and the day must be valid for the selected month and year.

Python also understands leap years. For example, February 29 is valid in 2024 because 2024 is a leap year. However, February 29 is not valid in 2025. Invalid dates cause a ValueError, helping programmers find mistakes early.

Example

from datetime import date
```

# Create different valid date objects

birthday = date(2014, 5, 20)
holiday = date(2026, 12, 25)
leap_day = date(2024, 2, 29)

print("Birthday:", birthday)
print("Holiday:", holiday)
print("Leap day:", leap_day)
```

Output

Birthday: 2014-05-20
```

Holiday: 2026-12-25
Leap day: 2024-02-29
```

Output Explanation

Each date is displayed in ISO format, which places the year first, followed by the month and day. Python automatically adds a leading zero to single-digit months and days when displaying the date.

```

24.5 Creating Time Objects

```

A time object represents a clock time without a calendar date. It can contain an hour, minute, second, and microsecond. The hour uses the 24-hour clock, so zero represents midnight and 23 represents 11 p.m.

Time objects are useful for opening hours, appointment times, class schedules, alarms, and daily routines. The values must be valid. Hours must be from 0 to 23, while minutes and seconds must be from 0 to 59.

Example

from datetime import time
```

# Create a time with only an hour and minute

opening_time = time(9, 30)

# Create a time with hour, minute, and second

closing_time = time(21, 15, 30)

# Create a time that includes microseconds

exact_time = time(14, 5, 10, 500000)

print("Opening:", opening_time)
print("Closing:", closing_time)
print("Exact time:", exact_time)
```

Output

Opening: 09:30:00
```

Closing: 21:15:30
Exact time: 14:05:10.500000
```

Output Explanation

Python displays time in hour-minute-second format. The first time is 9:30 a.m. The second is 9:15:30 p.m. using the 24-hour clock. The final value includes 500,000 microseconds, which equals half of one second.

```

24.6 Creating Datetime Objects

```

A datetime object combines a complete calendar date with a clock time. It normally contains a year, month, day, hour, minute, second, and optional microseconds. This type of object is useful when both the date and exact time of an event matter.

Datetime objects are commonly used for appointments, deliveries, event registrations, flight departures, online orders, and computer logs. You can access each part through attributes such as year, month, hour, and minute.

Example

from datetime import datetime
```

# Create a datetime object

appointment = datetime(2026, 8, 15, 14, 30, 0)

print("Appointment:", appointment)
print("Year:", appointment.year)
print("Month:", appointment.month)
print("Day:", appointment.day)
print("Hour:", appointment.hour)
print("Minute:", appointment.minute)
```

Output

Appointment: 2026-08-15 14:30:00
```

Year: 2026
Month: 8
Day: 15
Hour: 14
Minute: 30
```

Output Explanation

The full datetime value represents August 15, 2026, at 2:30 p.m. The remaining lines show how each individual part can be accessed. This is useful when a program needs to examine or display only one part of a datetime.

```

24.7 Formatting Dates

```

Python normally displays dates in a standard format, but users may prefer a more readable style. The strftime() method converts a date or datetime object into a formatted string. Special format codes determine how each part appears.

For example, %Y represents a four-digit year, %m represents the month number, %d represents the day, and %B represents the full month name. Formatting changes only how the date is displayed; it does not change the original object.

Common Formatting Codes

  • %Y – Four-digit year
  • %y – Two-digit year
  • %m – Month number
  • %B – Full month name
  • %b – Short month name
  • %d – Day of the month
  • %A – Full weekday name
  • %H – Hour using a 24-hour clock
  • %I – Hour using a 12-hour clock
  • %M – Minute
  • %S – Second
  • %p – AM or PM

Example

from datetime import datetime
```

event = datetime(2026, 12, 25, 18, 30)

print(event.strftime("%Y-%m-%d"))
print(event.strftime("%B %d, %Y"))
print(event.strftime("%A, %B %d, %Y"))
print(event.strftime("%I:%M %p"))
```

Output

2026-12-25
```

December 25, 2026
Friday, December 25, 2026
06:30 PM
```

Output Explanation

The same datetime object is displayed in four different ways. The first uses a numeric format, the second uses the full month name, the third adds the weekday, and the fourth displays the time using a 12-hour clock with PM.

```

24.8 Parsing Dates

```

Parsing means converting date text into a real datetime object. This is often necessary when a user enters a date in a form or when a program reads date information from a text file. The strptime() method performs this conversion.

The format passed to strptime() must match the text exactly. If the text is written as day/month/year, the format should use %d/%m/%Y. When the text and format do not match, Python raises a ValueError.

Example

from datetime import datetime
```

# Dates stored as text

date_text_1 = "25/12/2026"
date_text_2 = "July 19, 2026"

# Convert the strings into datetime objects

date_object_1 = datetime.strptime(date_text_1, "%d/%m/%Y")
date_object_2 = datetime.strptime(date_text_2, "%B %d, %Y")

print(date_object_1)
print(date_object_2)
```

Output

2026-12-25 00:00:00
```

2026-07-19 00:00:00
```

Output Explanation

Both strings are converted into datetime objects. Because the original text did not contain a time, Python uses midnight, shown as 00:00:00. After parsing, the values can be compared, formatted, or used in calculations.

```

24.9 Date Arithmetic

```

Date arithmetic means performing calculations with dates. Python can subtract one date from another to find the number of days between them. It can also add or subtract a time duration from a date to calculate a future or previous date.

Date arithmetic is useful for calculating ages, delivery dates, payment deadlines, membership periods, vacation lengths, and the number of days remaining before an event. Python handles different month lengths and leap years automatically.

Example

from datetime import date
```

start_date = date(2026, 7, 1)
end_date = date(2026, 7, 19)

# Subtract two dates

difference = end_date - start_date

print("Start date:", start_date)
print("End date:", end_date)
print("Days between:", difference.days)
```

Output

Start date: 2026-07-01
```

End date: 2026-07-19
Days between: 18
```

Output Explanation

Subtracting the start date from the end date produces a timedelta object. Its days attribute contains the number of complete days between the two dates, which is 18.

```

24.10 timedelta

```

A timedelta object represents a duration or difference between dates and times. It can store days, seconds, microseconds, milliseconds, minutes, hours, and weeks. It does not represent a specific date. Instead, it represents an amount of time.

You can add a timedelta to a date or datetime to move forward in time. You can subtract it to move backward. This is useful for calculating due dates, return dates, trial periods, reminders, and future appointments.

Example

from datetime import date, timedelta
```

today = date(2026, 7, 19)

# Create different time durations

one_week = timedelta(weeks=1)
thirty_days = timedelta(days=30)

# Add and subtract durations

next_week = today + one_week
thirty_days_later = today + thirty_days
one_week_ago = today - one_week

print("Today:", today)
print("Next week:", next_week)
print("Thirty days later:", thirty_days_later)
print("One week ago:", one_week_ago)
```

Output

Today: 2026-07-19
```

Next week: 2026-07-26
Thirty days later: 2026-08-18
One week ago: 2026-07-12
```

Output Explanation

Adding one week moves the date forward by seven days. Adding thirty days moves it into the next month. Subtracting one week produces the date seven days earlier. Python automatically handles the change from July to August.

```

24.11 Time Zones

```

Different parts of the world use different local times. A meeting at 3 p.m. in Toronto does not happen at 3 p.m. in London or Tokyo. A time zone describes the local time rules for a particular location, including its difference from UTC.

A datetime without time-zone information is called a naive datetime. A datetime that includes time-zone information is called an aware datetime. Aware datetime objects are safer for international applications because Python understands which location the time belongs to.

Example

from datetime import datetime, timezone, timedelta
```

# Create a fixed time zone that is 5 hours behind UTC

custom_zone = timezone(timedelta(hours=-5))

# Create an aware datetime

local_time = datetime(2026, 1, 15, 10, 30, tzinfo=custom_zone)

print("Local time:", local_time)
print("UTC offset:", local_time.utcoffset())
```

Output

Local time: 2026-01-15 10:30:00-05:00
```

UTC offset: -1 day, 19:00:00
```

Output Explanation

The -05:00 part shows that this time is five hours behind UTC. Python may display a negative five-hour duration as negative one day plus nineteen hours. Both representations describe the same offset.

```

24.12 UTC

```

UTC stands for Coordinated Universal Time. It is a worldwide time standard used to coordinate time between different countries and time zones. Unlike many local time zones, UTC does not move forward or backward for daylight saving time.

International applications often store dates and times in UTC. When displaying information to a user, the program converts the UTC time into the user's local time zone. This helps prevent confusion when users live in different parts of the world.

Example

from datetime import datetime, timezone
```

# Get the current date and time in UTC

utc_now = datetime.now(timezone.utc)

print("Current UTC time:", utc_now)
print("UTC time zone:", utc_now.tzinfo)
```

Example Output

Current UTC time: 2026-07-19 15:52:10.482013+00:00
```

UTC time zone: UTC
```

Output Explanation

The +00:00 at the end means that the datetime has no offset from UTC. The exact date and time will depend on when the program is run. The tzinfo value confirms that the object uses UTC.

```

24.13 zoneinfo

```

The zoneinfo module provides access to named time zones such as America/Toronto, Europe/London, and Asia/Tokyo. It is included in modern versions of Python and provides more accurate time-zone handling than using a fixed offset.

Named time zones understand daylight saving time rules. For example, Toronto may use a UTC offset of minus five hours during winter and minus four hours during summer. The zoneinfo module selects the correct offset based on the date.

Example

from datetime import datetime
```

from zoneinfo import ZoneInfo

# Create time-zone objects

toronto_zone = ZoneInfo("America/Toronto")
london_zone = ZoneInfo("Europe/London")
tokyo_zone = ZoneInfo("Asia/Tokyo")

# Create a datetime in Toronto

toronto_time = datetime(2026, 7, 19, 12, 0, tzinfo=toronto_zone)

# Convert the Toronto time to other time zones

london_time = toronto_time.astimezone(london_zone)
tokyo_time = toronto_time.astimezone(tokyo_zone)

print("Toronto:", toronto_time)
print("London:", london_time)
print("Tokyo:", tokyo_time)
```

Output

Toronto: 2026-07-19 12:00:00-04:00
```

London: 2026-07-19 17:00:00+01:00
Tokyo: 2026-07-20 01:00:00+09:00
```

Output Explanation

Noon in Toronto is 5 p.m. in London and 1 a.m. the next day in Tokyo for this example date. The offsets show the time-zone differences. Python also changes Tokyo's calendar date because the converted time passes midnight.

```

24.14 Unix Timestamps

```

A Unix timestamp is the number of seconds that have passed since January 1, 1970, at midnight UTC. Computers frequently use timestamps because they store a date and time as one number. This makes dates easy to save, compare, sort, and send between systems.

The timestamp() method converts a datetime object into a Unix timestamp. The fromtimestamp() method converts a Unix timestamp back into a datetime. The result may depend on the selected time zone.

Example

from datetime import datetime, timezone
```

# Create a UTC datetime

event_time = datetime(2026, 1, 1, 0, 0, tzinfo=timezone.utc)

# Convert the datetime to a Unix timestamp

unix_value = event_time.timestamp()

# Convert the timestamp back to a UTC datetime

converted_time = datetime.fromtimestamp(unix_value, timezone.utc)

print("Datetime:", event_time)
print("Unix timestamp:", unix_value)
print("Converted datetime:", converted_time)
```

Output

Datetime: 2026-01-01 00:00:00+00:00
```

Unix timestamp: 1767225600.0
Converted datetime: 2026-01-01 00:00:00+00:00
```

Output Explanation

The datetime is converted into the number of seconds since the Unix starting point. The timestamp is then converted back into the original UTC datetime, showing that the same moment can be represented as either a datetime object or a number.

```

24.15 Measuring Execution Time

```

Measuring execution time helps programmers understand how long a block of code takes to run. This is useful when comparing two solutions, improving a slow program, testing loops, or checking the performance of a function.

The time.perf_counter() function is a good choice for performance measurement because it provides a precise timer. The program records the time before the operation, records it again afterward, and subtracts the first value from the second.

Example

import time
```

# Record the starting time

start_time = time.perf_counter()

# Perform a calculation

total = 0

for number in range(1, 1000001):
total += number

# Record the ending time

end_time = time.perf_counter()

# Calculate the execution duration

duration = end_time - start_time

print("Total:", total)
print("Execution time:", duration, "seconds")
```

Example Output

Total: 500000500000
```

Execution time: 0.067412300000012 seconds
```

Output Explanation

The total is the sum of the numbers from 1 to 1,000,000. The execution time shows how many seconds the loop required. Your result will be different because execution speed depends on the computer, operating system, and current system activity.

```

24.16 The time Module

```

Python's time module provides functions related to system time, timestamps, delays, and performance measurement. It is different from the time class inside the datetime module. The module is imported using import time.

One commonly used function is time.sleep(), which pauses a program for a specified number of seconds. Another function, time.time(), returns the current Unix timestamp. Delays can be useful in countdowns, animations, repeated checks, and simple scheduling programs.

Example

import time
```

print("Program started")

# Pause the program for two seconds

time.sleep(2)

print("Two seconds have passed")

# Get the current Unix timestamp

current_timestamp = time.time()

print("Current timestamp:", current_timestamp)
```

Example Output

Program started
```

Two seconds have passed
Current timestamp: 1784477314.511274
```

Output Explanation

The program prints the first message and waits two seconds before printing the second message. The final value is the current Unix timestamp. Because the timestamp constantly increases, your value will be different.

```

24.17 Scheduling Concepts

```

Scheduling means arranging for a task to happen at a particular time or after a particular delay. A program may send a reminder, create a backup, display a notification, or run a report according to a schedule.

A simple Python program can check the current time repeatedly and run a task when a condition becomes true. However, large production applications normally use dedicated schedulers, operating-system services, task queues, or cloud scheduling tools. A basic loop is useful for learning the concept.

Example

from datetime import datetime, timedelta
```

import time

# Schedule a task three seconds from now

scheduled_time = datetime.now() + timedelta(seconds=3)

print("Task scheduled for:", scheduled_time.strftime("%H:%M:%S"))

while True:
current_time = datetime.now()

```
# Run the task when the scheduled time is reached
if current_time >= scheduled_time:
    print("Scheduled task is running.")
    break

# Wait briefly before checking again
time.sleep(0.5)

Example Output

Task scheduled for: 11:58:03
```

Scheduled task is running.
```

Output Explanation

The program calculates a time three seconds in the future. The loop checks the current time every half second. When the current time reaches or passes the scheduled time, the task message appears and the loop ends.

```

24.18 Practical Date Applications

```

Date and time skills can be combined to build useful applications. Common examples include age calculators, countdown timers, appointment systems, delivery estimators, attendance trackers, subscription systems, and event reminders.

In this example, the program calculates the number of days remaining before an event. It uses the current date and an event date. If the event is in the future, the program displays the number of remaining days. If the event has passed, it displays a different message.

Example: Event Countdown

from datetime import date
```

# Get today's date

today = date.today()

# Set the event date

event_date = date(2026, 12, 25)

# Calculate the difference

difference = event_date - today

if difference.days > 0:
print(difference.days, "days remain before the event.")
elif difference.days == 0:
print("The event is today!")
else:
print("The event has already passed.")
```

Example Output

159 days remain before the event.

Output Explanation

The program subtracts today's date from the event date. A positive result means the event is still in the future. A result of zero means the event is today, and a negative result means the event has already passed.

```

24.19 Chapter Practice Exercises

```

The following exercises help you practise the main ideas in this chapter. Try writing each program before looking at other examples. Begin with simple date creation and formatting, and then move to calculations, time zones, and practical applications.

  1. Create a date object for your next birthday and print it.
  2. Display the current local date using date.today().
  3. Display the current date and time using datetime.now().
  4. Create a time object representing 8:45 a.m.
  5. Create a datetime object for December 31, 2026, at 11:59 p.m.
  6. Format a date as Month Day, Year.
  7. Format a datetime using a 12-hour clock with AM or PM.
  8. Convert the string 15-08-2026 into a datetime object.
  9. Calculate the number of days between two dates.
  10. Add 14 days to the current date.
  11. Subtract one week from a selected date.
  12. Display the current UTC date and time.
  13. Convert Toronto time into London time using zoneinfo.
  14. Convert a datetime object into a Unix timestamp.
  15. Convert a Unix timestamp back into a datetime object.
  16. Measure how long a loop takes using time.perf_counter().
  17. Pause a program for three seconds using time.sleep().
  18. Create a five-second countdown timer.
  19. Calculate how many days remain until January 1, 2027.
  20. Create an appointment reminder using a datetime and a timedelta.

Practice Example: Five-Second Countdown

import time
```

# Count backward from five to one

for number in range(5, 0, -1):
print(number)
time.sleep(1)

print("Time is up!")
```

Output

5
```

4
3
2
1
Time is up!
```

Output Explanation

The range(5, 0, -1) expression produces the numbers from five down to one. After printing each number, the program pauses for one second. When the loop finishes, the final message is displayed.

```

24.20 Chapter Mini Project

```

Project: Personal Event Countdown

In this mini project, you will create a personal event countdown program. The user enters an event name and date. The program converts the entered text into a date object, compares it with today's date, and reports whether the event is in the future, happening today, or already finished.

This project combines user input, date parsing, date arithmetic, conditional statements, exception handling, and date formatting. It also handles invalid date entries so that the program does not crash when the user enters an incorrect format or an impossible date.

Complete Program

# Import the required classes
```

from datetime import datetime, date

print("Personal Event Countdown")
print("------------------------")

# Ask the user for the event information

event_name = input("Enter the event name: ")
event_date_text = input("Enter the event date (YYYY-MM-DD): ")

try:
# Convert the entered text into a datetime object
event_datetime = datetime.strptime(event_date_text, "%Y-%m-%d")

```
# Extract only the date portion
event_date = event_datetime.date()

# Get today's local date
today = date.today()

# Calculate the difference
difference = event_date - today

# Display the formatted event date
formatted_date = event_date.strftime("%A, %B %d, %Y")

print()
print("Event:", event_name)
print("Date:", formatted_date)

# Check whether the event is in the future, today, or past
if difference.days > 1:
    print(difference.days, "days remain before the event.")

elif difference.days == 1:
    print("The event is tomorrow.")

elif difference.days == 0:
    print("The event is today!")

else:
    days_passed = abs(difference.days)
    print("The event passed", days_passed, "days ago.")
```

except ValueError:
print()
print("Invalid date.")
print("Please enter a real date using the YYYY-MM-DD format.")
```

Example Run 1

Personal Event Countdown
```

---

Enter the event name: Winter Celebration
Enter the event date (YYYY-MM-DD): 2026-12-25

Event: Winter Celebration
Date: Friday, December 25, 2026
159 days remain before the event.
```

Example Run 2

Personal Event Countdown
```

---

Enter the event name: Birthday Party
Enter the event date (YYYY-MM-DD): 2026-02-30

Invalid date.
Please enter a real date using the YYYY-MM-DD format.
```

Project Explanation

The program first asks for an event name and a date. The entered date is initially ordinary text. The strptime() method converts that text into a datetime object using the required year-month-day format.

The date() method extracts the calendar date from the datetime object. The program then subtracts today's date from the event date. The result is a timedelta object whose days value shows whether the event is in the future, today, or in the past.

The try and except blocks protect the program from invalid dates. For example, February 30 does not exist, so Python raises a ValueError. Instead of stopping the program, the exception handler displays a helpful error message.

How to Run the Mini Project

  1. Open Visual Studio Code, IDLE, PyCharm, or another Python editor.
  2. Create a new file named event_countdown.py.
  3. Copy the complete project code into the file.
  4. Save the file.
  5. Open a terminal in the folder containing the file.
  6. Run the program using python event_countdown.py.
  7. On some computers, use python3 event_countdown.py.
  8. Enter an event name when requested.
  9. Enter a valid date using the YYYY-MM-DD format.
  10. Read the countdown result displayed by the program.

Project Challenges

  • Allow the user to enter several events.
  • Save events in a text file.
  • Sort events from the nearest date to the farthest date.
  • Display only future events.
  • Add an event time as well as an event date.
  • Allow the user to select a time zone.
  • Display the remaining time in days and hours.
  • Create a menu for adding, viewing, and deleting events.
```
Chapter 2: Development EnvironmentPrepare Your JavaScript Workspace

A modern course built to help learners study step by step with clarity, comfort, and confidence.