Reading history

Python datetime: Dates, Times, Formatting and Time Zones

3 min read 2 views

Learn Python datetime: date and datetime objects, strftime and strptime format codes, timedelta arithmetic and time zones with zoneinfo.

Deadlines, birthdays, timestamps and opening hours all need dates and times. Python’s built-in datetime module creates them, formats them as text, reads them back from text, and does arithmetic such as “30 days from now” or “hours between two times”. The zoneinfo module adds proper time zones. This lesson covers all of it with tested examples.

In this lesson you will learn

  • How to create date and datetime objects
  • How to format them with strftime()
  • How to read dates from text with strptime()
  • Date arithmetic with timedelta
  • How to work with time zones

Creating, Formatting and Parsing

from datetime import date, datetime, timedelta

exam = date(2026, 12, 16)
print(exam, exam.year, exam.strftime("%A"))

moment = datetime(2026, 11, 15, 19, 30)
print(moment.strftime("%d/%m/%Y %I:%M %p"))

parsed = datetime.strptime("25-12-2026 08:15", "%d-%m-%Y %H:%M")
print(parsed)

print(exam + timedelta(days=30))
gap = date(2027, 1, 1) - date(2026, 11, 15)
print(gap.days, "days")

Output

2026-12-16 2026 Wednesday
15/11/2026 07:30 PM
2026-12-25 08:15:00
2027-01-15
47 days
  • date(year, month, day) holds a calendar date; datetime adds hours and minutes. Use date.today() or datetime.now() for the current moment.
  • strftime() (“string format time”) turns a date into text using codes like %d.
  • strptime() (“string parse time”) does the reverse: it reads text in a given format.
  • Adding a timedelta moves a date forward; subtracting two dates gives a timedelta whose .days is the gap.

Common Format Codes

CodeMeaningExample
%Y / %yYear, 4 or 2 digits2026 / 26
%mMonth number12
%B / %bMonth name, full / shortDecember / Dec
%dDay of the month16
%A / %aWeekday, full / shortWednesday / Wed
%H / %IHour, 24-hour / 12-hour19 / 07
%M, %SMinutes, seconds30, 00
%pAM or PMPM

Time Zones and Durations

from datetime import datetime, timezone, timedelta
from zoneinfo import ZoneInfo

meeting = datetime(2026, 11, 20, 15, 0, tzinfo=ZoneInfo("Asia/Dhaka"))
print(meeting.isoformat())
print(meeting.astimezone(ZoneInfo("Europe/London")).strftime("%H:%M %Z"))
print(meeting.astimezone(timezone.utc).strftime("%H:%M UTC"))

start = datetime(2026, 11, 15, 9, 0)
end = datetime(2026, 11, 15, 17, 45)
worked = end - start
print(worked, worked.total_seconds() / 3600, "hours")
print((start + timedelta(weeks=1)).date())

Output

2026-11-20T15:00:00+06:00
09:00 GMT
09:00 UTC
8:45:00 8.75 hours
2026-11-22
  • ZoneInfo("Asia/Dhaka") attaches a real time zone; .isoformat() shows the offset (+06:00).
  • .astimezone() converts the same moment to another zone: 3 pm in Dhaka is 9 am in London and in UTC in November.
  • timedelta supports days, hours, minutes and weeks; .total_seconds() converts a duration to a number.

Store times in UTC

A common rule for apps is to store every timestamp in UTC and convert to the user’s zone only when displaying it. That avoids daylight-saving surprises.

Common Mistakes

  1. Mixing up %m (month) and %M (minute).
  2. Comparing “naive” and “aware” datetimes (without and with a time zone), which raises TypeError.
  3. Adding months with timedelta. It has no month unit because months differ in length; use the dateutil package for that.
  4. Using a strptime format that does not exactly match the text, which raises ValueError.

Practice Exercises

Exercise 1. Work out someone’s age in whole years from a birth date of 15 August 2004, on 15 November 2026.

Show answer
from datetime import date
born, today = date(2004, 8, 15), date(2026, 11, 15)
age = today.year - born.year - ((today.month, today.day) < (born.month, born.day))
print(age)   # 22

Exercise 2. Print today’s date as “Sunday, 15 Nov 2026”.

Show answer
from datetime import date
print(date.today().strftime("%A, %d %b %Y"))

Frequently Asked Questions

How do I get the current date and time in Python?

Use datetime.now(), or datetime.now(ZoneInfo("Asia/Dhaka")) for a time-zone-aware value. date.today() gives the date only.

How do I get a Unix timestamp?

Call .timestamp() on a datetime. To go back, use datetime.fromtimestamp(ts).

Summary

  • date and datetime represent calendar dates and moments.
  • strftime formats; strptime parses.
  • timedelta adds, subtracts and measures durations.
  • zoneinfo handles time zones; store times in UTC.

Related: Python Modules.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *