1. Home
  2. Blog
  3. Software Development

Software Development

Python Datetime Explained: Format, Parse and Handle Time Zones

Python datetime handles dates, times and durations, but naive times, format codes and daylight saving cause real bugs. Learn strftime, strptime, timedelta, ISO 8601 and zoneinfo with output from tested code, plus the traps to avoid.

9 min read
Python datetime explained: formatting, parsing and time zones

Key takeaways

  • The Python datetime module gives you date, time, datetime, timedelta and timezone.
  • strftime() turns a datetime into text, strptime() turns text into a datetime, and the format must match exactly.
  • Store and compare times as aware UTC values. Python refuses to compare naive and aware datetimes.
  • Use zoneinfo for real time zones. On Windows, install the tzdata package first, or zone lookups fail.

Dates look simple until a report shows yesterday’s orders as today’s, a meeting reminder fires an hour late after the clocks change, or a log parser crashes on a date written the other way round. The Python datetime module has everything you need to avoid these bugs, as long as you know which tool to pick.

This guide walks through the module the way you use it at work: creating values, formatting and parsing, date arithmetic, time zones and timestamps. All output comes from Python 3.13.6 on our machine, with tzdata 2026.6 installed for zone data.

The main types

Type Holds Example use
date Year, month, day Birthdays, due dates
time Hour to microsecond Opening hours
datetime Date plus time, optional zone Events, logs, orders
timedelta A duration “In 20 days”, time taken
timezone A fixed UTC offset UTC itself, fixed offsets

Most code imports the classes directly: from datetime import datetime, date, timedelta, timezone. The module and the class share the name datetime, which causes the common error module 'datetime' has no attribute 'now'. If you write import datetime, you must call datetime.datetime.now().

Creating datetimes

from datetime import datetime, date, timedelta, timezone

d = datetime(2026, 11, 16, 9, 30)
print(d.isoformat(), d.tzinfo)
# 2026-11-16T09:30:00 None

The None matters: this value has no time zone. Python calls it naive. Other ways to get a datetime are datetime.now() for the local clock, datetime.now(timezone.utc) for the current UTC time with a zone attached, and date.today() for just the date.

Formatting with strftime

strftime() (string format time) builds text from a datetime using format codes:

print(d.strftime("%d %b %Y, %H:%M"), d.strftime("%A"))
# 16 Nov 2026, 09:30 Monday

The codes you will use most:

Code Meaning Example
%Y 4-digit year 2026
%m Month, zero padded 11
%d Day, zero padded 16
%H / %I Hour, 24h / 12h 09
%M / %S Minute / second 30
%p AM or PM AM
%b / %B Month name short / full Nov / November
%a / %A Weekday short / full Mon / Monday
%z UTC offset +0000

A classic slip is mixing up %m (month) and %M (minute). Month and weekday names follow the current locale, so be careful when output must be machine-readable. In f-strings you can skip the method call: f"{d:%Y-%m-%d}" works too, as our f-strings guide shows.

Parsing with strptime

strptime() (string parse time) is the reverse. You describe the input format, and Python builds the datetime:

p = datetime.strptime("16/11/2026 18:05", "%d/%m/%Y %H:%M")
print(repr(p))
# datetime.datetime(2026, 11, 16, 18, 5)

datetime.strptime("2026-11-16", "%d/%m/%Y")
# ValueError: time data '2026-11-16' does not match format '%d/%m/%Y'

The match must be exact, including separators. That strictness is useful: wrap parsing of user input in try/except ValueError and show a clear message, as covered in our exception handling guide. Never guess between day-first and month-first formats. “03/04/2026” is March in one country and April in another.

ISO 8601: the format to default to

For anything stored or sent between systems, use ISO 8601. It sorts correctly as text, and Python reads it without a format string:

print(datetime.fromisoformat("2026-11-16T09:30:00+05:30"))
# 2026-11-16 09:30:00+05:30

isoformat() writes it and fromisoformat() reads it. Since Python 3.11, fromisoformat() accepts most ISO 8601 strings, including a trailing Z for UTC. JSON APIs nearly always use this format, so it pairs well with our Python JSON guide.

Date math with timedelta

A timedelta is a duration. Add it to a datetime to move forward, or subtract two datetimes to get one:

print(d + timedelta(days=20, hours=5))
# 2026-12-06 14:30:00
print(date(2026, 12, 25) - date(2026, 11, 16))
# 39 days, 0:00:00
shift = datetime(2026, 11, 16, 18, 0) - datetime(2026, 11, 16, 9, 30)
print(shift.total_seconds() / 3600)
# 8.5

Use total_seconds() to convert a duration into a plain number. The .seconds attribute is a trap: it only holds the seconds part left over after whole days, so a 2-day duration has .seconds == 0.

Naive vs aware datetimes

A naive datetime has no zone. An aware one carries a tzinfo, so it points to one exact moment. Python will not guess how they relate:

u = datetime(2026, 11, 16, 4, 0, tzinfo=timezone.utc)
print(d < u)
# TypeError: can't compare offset-naive and offset-aware datetimes

This error is a gift. It stops you from comparing “9:30 somewhere” with “4:00 UTC”. The fix is to make every datetime aware as early as possible, ideally the moment it enters your program.

Time zones with zoneinfo

The built-in timezone class only handles fixed offsets. Real places change offset for daylight saving, so use zoneinfo (standard since Python 3.9) with IANA names:

from zoneinfo import ZoneInfo
u = datetime(2026, 11, 16, 4, 0, tzinfo=timezone.utc)
print(u.astimezone(ZoneInfo("Asia/Kolkata")))
print(u.astimezone(ZoneInfo("America/New_York")))
# 2026-11-16 09:30:00+05:30
# 2026-11-15 23:00:00-05:00

The same moment is Monday morning in Kolkata and still Sunday night in New York. That is exactly why “today’s orders” reports go wrong when they use the server’s zone instead of the customer’s.

Windows tip: our first run failed with ZoneInfoNotFoundError: 'No time zone found with key Asia/Kolkata'. Windows has no system time zone database, so run pip install tzdata. Linux and macOS usually have zone data already.

The daylight saving trap

In New York, clocks jumped forward on 8 March 2026. Watch what adding one day does across that change:

ny = ZoneInfo("America/New_York")
a = datetime(2026, 3, 7, 12, tzinfo=ny)
b = a + timedelta(days=1)
print(b, b.utcoffset())
# 2026-03-08 12:00:00-04:00 -1 day, 20:00:00

The wall clock moved by exactly one day, to noon again, but the offset changed from -5 to -4 hours. Only 23 real hours passed. Python does wall-clock arithmetic within a zone. If you need exact elapsed time, convert to UTC, do the math there, and convert back for display.

Timestamps

A Unix timestamp counts seconds since 1 January 1970 UTC. Convert both ways with an explicit zone:

print(int(u.timestamp()))
# 1794801600
print(datetime.fromtimestamp(1794801600, tz=timezone.utc))
# 2026-11-16 04:00:00+00:00

Without tz=, fromtimestamp() returns naive local time, which differs from machine to machine. Also note that datetime.utcfromtimestamp() and datetime.utcnow() are deprecated because they return naive values that look like UTC but are not marked as such.

Adding months and years

timedelta has no months argument, because months have different lengths. Adding 30 days is not “one month later”:

print(date(2026, 1, 31) + timedelta(days=30))
# 2026-03-02

For calendar months, decide the business rule first. Does 31 January plus one month mean 28 February or 3 March? The third-party dateutil.relativedelta picks the last valid day, which suits most billing cases. Whatever you choose, write tests for month-end dates and 29 February.

Best practices

  1. Store UTC, display local. Keep aware UTC datetimes in databases and logs, and convert to the user’s zone only for display.
  2. Use ISO 8601 for text. It is unambiguous and sorts correctly.
  3. Use datetime.now(timezone.utc), not utcnow().
  4. Use zoneinfo names such as Europe/London, not fixed offsets, for real places.
  5. Measure durations with time.monotonic() when timing code, since the wall clock can jump.
  6. Test the edges: month ends, leap days, DST changes and midnight. Our SQL date functions guide covers the database side.

Testing code that depends on the current time

Code that calls datetime.now() inside a function is hard to test, because the answer changes every second. The simplest fix needs no library: let the caller pass in the current time, and fall back to the real clock only when nothing is given.

from datetime import datetime, timezone

def is_overdue(due, now=None):
    now = now or datetime.now(timezone.utc)
    return now > due

due = datetime(2026, 11, 20, tzinfo=timezone.utc)
print(is_overdue(due, now=datetime(2026, 11, 19, tzinfo=timezone.utc)))  # False
print(is_overdue(due, now=datetime(2026, 11, 21, tzinfo=timezone.utc)))  # True

Both results came from our run. Tests can now check the day before, the day after and the exact boundary without waiting or mocking. When you cannot change the function signature, libraries such as freezegun and time-machine freeze the clock during a test, and our Python mocking guide shows how to patch datetime with unittest.mock. Whichever route you pick, put the tricky dates from the best practices list into a parametrized test so they run on every build.

Final thoughts

Python datetime is reliable once you follow a few rules. Format with strftime, parse with strptime or fromisoformat, use timedelta for durations, and keep every value aware, preferably in UTC. Reach for zoneinfo when people and places are involved, remember tzdata on Windows, and treat daylight saving as a test case rather than a surprise.

FAQ

What is the difference between strftime and strptime?

strftime formats a datetime object into a string. strptime parses a string into a datetime object using a format you describe.

How do I get the current time in UTC in Python?

Call datetime.now(timezone.utc). It returns an aware datetime marked as UTC. Avoid datetime.utcnow because it is deprecated and returns a naive value.

What is a naive datetime in Python?

A naive datetime has no time zone attached, so it does not point to one exact moment. Python refuses to compare it with an aware datetime.

How do I add months to a date in Python?

timedelta has no months argument. Use dateutil.relativedelta or write your own rule for month ends, and test dates such as 31 January.

Why does zoneinfo fail on Windows?

Windows does not ship the IANA time zone database that zoneinfo reads. Install the tzdata package with pip and the zone names will work.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
Software Development

Unix Timestamp Explained: Seconds vs ms

A Unix timestamp counts seconds since 1 January 1970 UTC. Learn seconds vs milliseconds, converting in Python, JavaScript and SQL,…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Software Development

JavaScript Date: Format, Parse, Timezone Bugs

JavaScript Date explained with tested Node.js code: zero-based months, the date-only UTC parsing trap, toISOString, getTimezoneOffset, Intl formatting, date math…

Read article →
Software Development

Python Requests: GET, POST, Timeouts, Retries

Python requests explained with code tested against a local API: GET with params, POST json vs data, headers and auth,…

Read article →
Software Development

Python Deepcopy vs Copy: Fix Nested Lists

Python deepcopy vs shallow copy explained with tested code: aliasing, nested lists, the [[0]*3]*3 trap, memo and cycles, custom __deepcopy__,…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
Software Development

Base64 Encoding Explained, With Python Code

Base64 encoding turns bytes into 64 safe text characters. See the bit-level steps, padding, URL-safe base64, the 33% size cost,…

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Databases & SQL

SQL LAG and LEAD: Compare Rows, 5 Examples

SQL LAG and LEAD read values from the previous or next row without a self join. Five tested examples: change,…

Read article →
Databases & SQL

SQL STRING_AGG: Combine Rows Into One String

SQL STRING_AGG joins values from many rows into one string per group. See syntax for PostgreSQL, SQL Server, MySQL GROUP_CONCAT,…

Read article →
Software Development

JavaScript Classes: Private Fields and Extends

JavaScript classes explained with tested Node.js code: constructors, methods, #private fields, getters, static members, extends and super, plus the errors…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →