KAHIBARO Bookshelves
Discord Login Register

12.3.3. datetime

Working with `datetime`

The datetime module in Python’s standard library helps you work with dates, times, and time intervals. It is useful any time you need to record “when” something happens, calculate durations, or format dates and times nicely.

You typically start with:

import datetime

or, for convenience:

from datetime import date, time, datetime, timedelta

In this chapter, we’ll focus on the most commonly used parts: date, time, datetime, timedelta, and basic formatting/parsing.


Dates with `date`

A date represents a calendar date (year, month, day) without any time of day.

Creating dates

from datetime import date
# Today's date
today = date.today()
print(today)             # e.g. 2025-03-15
# A specific date: year, month, day
birthday = date(2000, 5, 20)
print(birthday)          # 2000-05-20

You can access parts of the date:

print(today.year)        # e.g. 2025
print(today.month)       # 3
print(today.day)         # 15

Comparing dates

You can compare date objects with comparison operators:

if today > birthday:
    print("Today is after your birthday.")

This works because date objects know how to compare themselves.


Times with `time`

A time represents a time of day (hours, minutes, seconds, microseconds) without any date.

Creating times

from datetime import time
# hour, minute, second
start = time(9, 30, 0)
print(start)             # 09:30:00
# Only hour and minute
evening = time(18, 45)
print(evening)           # 18:45:00

You can access components:

print(start.hour)        # 9
print(start.minute)      # 30
print(start.second)      # 0

Date and time together: `datetime`

A datetime combines both date and time in one object.

Getting the current date and time

from datetime import datetime
now = datetime.now()
print(now)               # e.g. 2025-03-15 14:27:53.123456

datetime.now() gives the current local date and time.

You can also get just the current date or time from a datetime:

print(now.date())        # e.g. 2025-03-15
print(now.time())        # e.g. 14:27:53.123456

Creating a specific `datetime`

meeting = datetime(2025, 4, 1, 10, 30, 0)
print(meeting)           # 2025-04-01 10:30:00
print(meeting.year)      # 2025
print(meeting.month)     # 4
print(meeting.day)       # 1
print(meeting.hour)      # 10
print(meeting.minute)    # 30

Comparing `datetime` values

You can compare datetime objects just like date:

deadline = datetime(2025, 4, 1, 23, 59)
if now > deadline:
    print("Deadline has passed.")
else:
    print("You still have time!")

Time differences with `timedelta`

timedelta represents a duration (a difference between two moments in time). You can:

  • Subtract two date or datetime objects to get a timedelta
  • Add or subtract a timedelta from a date or datetime

Subtracting dates and datetimes

from datetime import date, datetime, timedelta
today = date.today()
future = date(2025, 12, 31)
difference = future - today
print(difference)        # e.g. 291 days, 0:00:00
print(difference.days)   # e.g. 291

With datetime:

now = datetime.now()
event = datetime(2025, 6, 1, 12, 0)
time_left = event - now
print(time_left)         # e.g. 78 days, 21:15:03.123456
print(time_left.days)    # whole days
print(time_left.seconds) # remaining seconds after days

Creating and using `timedelta`

You can create durations:

one_day = timedelta(days=1)
two_hours = timedelta(hours=2)
mix = timedelta(days=2, hours=3, minutes=30)

Common use: add or subtract a timedelta:

today = date.today()
tomorrow = today + timedelta(days=1)
yesterday = today - timedelta(days=1)
print(tomorrow)
print(yesterday)

A simple reminder system example:

event = datetime(2025, 5, 10, 9, 0)
reminder_time = event - timedelta(hours=1)
print("Reminder at:", reminder_time)

Formatting dates and times as strings

Often you need to show a date/time to a user in a friendly format (for example, “01/04/2025 10:30 AM”) or save it in a particular pattern. This is done with strftime (“string format time”).

`strftime` basics

You call .strftime(format_string) on a date or datetime object. The format_string contains special codes that represent parts of the date/time.

Common codes:

  • %Y – 4-digit year (e.g. 2025)
  • %m – 2-digit month (01–12)
  • %d – 2-digit day (01–31)
  • %H – hour (00–23)
  • %I – hour (01–12)
  • %M – minute (00–59)
  • %S – second (00–59)
  • %p – AM/PM
  • %A – full weekday name (e.g. Monday)
  • %B – full month name (e.g. January)

Examples

from datetime import datetime
now = datetime.now()
# Simple date
print(now.strftime("%Y-%m-%d"))       # 2025-03-15
# Day/Month/Year
print(now.strftime("%d/%m/%Y"))       # 15/03/2025
# Full date with words
print(now.strftime("%A, %B %d, %Y"))
# e.g. Saturday, March 15, 2025
# Time in 24-hour format
print(now.strftime("%H:%M:%S"))       # 14:30:05
# Time in 12-hour format with AM/PM
print(now.strftime("%I:%M %p"))       # 02:30 PM

You can mix text and codes:

message = now.strftime("Backup created on %Y-%m-%d at %H:%M")
print(message)

Turning strings into dates and times (`strptime`)

Sometimes you receive a date/time as a string (for example, from user input or a file) and you want to convert it into a datetime object. Use strptime (“string parse time”).

You must tell Python what pattern the string follows, using the same codes as strftime.

Basic usage

from datetime import datetime
text = "2025-04-01 10:30"
dt = datetime.strptime(text, "%Y-%m-%d %H:%M")
print(dt)            # 2025-04-01 10:30:00
print(type(dt))      # <class 'datetime.datetime'>

Another example with different format

birthday_text = "20/05/2000"
birthday = datetime.strptime(birthday_text, "%d/%m/%Y")
print(birthday.date())    # 2000-05-20

Common mistake: the format string must match exactly the input string.

For example, this will fail:

text = "2025/04/01"
# Wrong: using '-' instead of '/'
# dt = datetime.strptime(text, "%Y-%m-%d")  # ValueError
# Correct:
dt = datetime.strptime(text, "%Y/%m/%d")

Simple practical examples

Countdown until a future date

from datetime import date
today = date.today()
holiday = date(2025, 12, 25)
days_left = (holiday - today).days
print("Days until holiday:", days_left)

Adding days to a date (e.g. due date)

from datetime import date, timedelta
borrow_date = date.today()
loan_period = timedelta(days=14)
due_date = borrow_date + loan_period
print("Borrow date:", borrow_date)
print("Due date:", due_date)

Logging with timestamps

from datetime import datetime
def log(message):
    now = datetime.now()
    timestamp = now.strftime("%Y-%m-%d %H:%M:%S")
    print(f"[{timestamp}] {message}")
log("Program started")
log("Something happened")

This produces output like:

[2025-03-15 14:45:10] Program started
[2025-03-15 14:45:11] Something happened

Summary

  • date handles calendar dates (year, month, day).
  • time handles times of day (hour, minute, second).
  • datetime combines both date and time.
  • timedelta represents durations and is used for adding/subtracting time.
  • .strftime() formats date/time objects as strings.
  • datetime.strptime() parses strings into datetime objects when you know the format.

These tools cover most everyday tasks involving dates and times in Python and are often enough for simple scripts, logs, reminders, and basic scheduling.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms