Python

Python Date and Time

Python provides powerful tools for working with dates and times through the built-in datetime module. This module allows you to:

  • Represent dates and times
  • Format and parse date/time strings
  • Perform date/time arithmetic
  • Work with timezones
  • Get the current date/time

Learn Python Programming and become a certified software developer

Let’s break it down.

1. Importing the datetime module

import datetime

You can also import specific classes:

Learn Python Programming Online

from datetime import date, time, datetime, timedelta

2. Working with Dates

The date class represents a calendar date (year, month, day).

Create a Date

from datetime import date

d = date(2025, 12, 1)
print(d)   # 2025-12-01

Get Today’s Date

today = date.today()
print(today)   # Example: 2025-12-01

Date Attributes

print(today.year)
print(today.month)
print(today.day)

3. Working with Time

The time class represents a time of day (without date).

Create a Time

from datetime import time

t = time(14, 30, 45)
print(t)  # 14:30:45

Time Attributes

print(t.hour)
print(t.minute)
print(t.second)
print(t.microsecond)

4. Working with DateTime

The datetime class combines both date + time.

Create a datetime

from datetime import datetime

dt = datetime(2025, 12, 1, 14, 30, 45)
print(dt)

Current DateTime

now = datetime.now()
print(now)

UTC Time

utc_now = datetime.utcnow()
print(utc_now)

5. Formatting Dates and Times (strftime)

Use .strftime() to convert a date/time object into a formatted string.

Common Format Codes

  • %Y → Year
  • %m → Month
  • %d → Day
  • %H → Hour
  • %M → Minute
  • %S → Second
  • %A → Day name

Example

now = datetime.now()

formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted)

6. Parsing Strings into DateTime (strptime)

Use .strptime() to convert a string into a datetime object.

from datetime import datetime

date_string = "2025-12-01 14:30:45"
parsed = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")

print(parsed)

7. Date and Time Arithmetic

Python uses timedelta for arithmetic.

Adding Days

from datetime import timedelta

future = today + timedelta(days=10)
print(future)

Subtracting Days

past = today - timedelta(days=7)
print(past)

Difference Between Two Dates

d1 = date(2025, 1, 1)
d2 = date(2025, 12, 1)

diff = d2 - d1
print(diff.days)  # number of days

8. Working With Timezones (zoneinfo)

Python 3.9+ uses zoneinfo for timezone support.

from datetime import datetime
from zoneinfo import ZoneInfo

lagos_time = datetime.now(ZoneInfo("Africa/Lagos"))
print(lagos_time)

new_york_time = datetime.now(ZoneInfo("America/New_York"))
print(new_york_time)

Convert Between Timezones

dt = datetime(2025, 12, 1, 14, 0, tzinfo=ZoneInfo("Africa/Lagos"))
converted = dt.astimezone(ZoneInfo("America/New_York"))
print(converted)

9. Sleep / Delay with Time Module

Sometimes you need delays (not part of datetime).

import time

time.sleep(2)  # pause for 2 seconds

10. Best Practices

✔ Use datetime for timestamps

✔ Use zoneinfo instead of old pytz

✔ Always convert to UTC for storage

✔ Use .strftime() and .strptime() for formatting/parsing

✔ Use timedelta for safe arithmetic

Share
Published by
codeflare

Recent Posts

Costly Linux Mistakes Beginners Make

1. Running Everything as Root One of the biggest beginner errors. Many new users log…

2 weeks ago

How Keyloggers Work

A keylogger is a type of surveillance software or hardware that records every keystroke made…

3 weeks ago

JavaScript Memoization

In JavaScript, it’s commonly used for: Recursive functions (like Fibonacci) Heavy calculations Repeated API/data processing…

1 month ago

CSS Container Queries: Responsive Design That Actually Makes Sense

For years, responsive design has depended almost entirely on media queries. We ask questions like: “If…

1 month ago

Cron Jobs & Task Scheduling

1. What is Task Scheduling? Task scheduling is the process of automatically running commands, scripts,…

1 month ago

Differences Between a Website and a Web App

Here’s a comprehensive, clear differentiation between a Website and a Web App, from purpose all the…

2 months ago