Python datetime

Generate Python date/time code for the standard library, dateutil, and arrow. Pick a module and operation — get copy-ready code instantly.

-- Select a module and operation above

How to Use This Tool

Select a Python module from the tabs — the standard library datetime, the popular dateutil extension, or the human-friendly arrow library. Then choose an operation from the chip selector. The tool generates practical, copy-ready Python code with real-world examples and comments explaining each step.

This is especially useful when you can never remember whether it's strftime or strptime, what format code gives you a zero-padded month, or how to properly handle timezones. Instead of digging through docs, pick your operation and copy the code.

strftime / strptime Format Codes

The complete reference for Python's date formatting and parsing. These codes work with both strftime() (format to string) and strptime() (parse from string).

CodeMeaningExample
%Y4-digit year2026
%y2-digit year26
%mMonth (zero-padded)03
%BFull month nameMarch
%bAbbreviated monthMar
%dDay of month (zero-padded)26
%jDay of year (001–366)085
%HHour, 24-hour (zero-padded)14
%IHour, 12-hour (zero-padded)02
%MMinute (zero-padded)30
%SSecond (zero-padded)45
%fMicrosecond (000000–999999)123456
%pAM / PMPM
%AFull weekday nameThursday
%aAbbreviated weekdayThu
%wWeekday number (0=Sun, 6=Sat)4
%uISO weekday (1=Mon, 7=Sun)4
%UWeek number (Sun start)12
%WWeek number (Mon start)12
%VISO week number13
%zUTC offset (+HHMM)-0500
%ZTimezone nameEST
%cLocale date+timeThu Mar 26 14:30:45 2026
%xLocale date03/26/26
%XLocale time14:30:45
%%Literal %%

Common Format Patterns

Patternstrftime CodeOutput
ISO 8601%Y-%m-%dT%H:%M:%S2026-03-26T14:30:45
US date%m/%d/%Y03/26/2026
EU date%d/%m/%Y26/03/2026
Long date%B %d, %YMarch 26, 2026
Short date%b %d, %YMar 26, 2026
24-hour time%H:%M:%S14:30:45
12-hour time%I:%M %p02:30 PM
Full timestamp%Y-%m-%d %H:%M:%S2026-03-26 14:30:45
Log format%d/%b/%Y:%H:%M:%S %z26/Mar/2026:14:30:45 -0500

Module Comparison

When to use each library, and what it costs.

Featuredatetime (stdlib)dateutilarrow
InstallBuilt-inpip install python-dateutilpip install arrow
Create datesdatetime(), date()parse() — flexible string parsingarrow.now(), arrow.get()
Add months/yearsNo (only timedelta: days/seconds)relativedelta(months=3)shift(months=3)
Timezone handlingzoneinfo (3.9+) or pytztz.gettz(), tz.UTCBuilt-in .to('US/Eastern')
Flexible parsingstrptime (strict format required)parser.parse() (auto-detect format)arrow.get() (auto or format)
Human-readableManual formattingManual formatting.humanize() → "2 hours ago"
Best forStandard operations, no dependenciesComplex date math, flexible parsingHuman-friendly API, quick scripts

Timezone Handling

Timezones are the most common source of datetime bugs in Python. Here's what you need to know.

Naive vs Aware datetimes

A naive datetime has no timezone info — dt.tzinfo is None. It's just a date and time floating in space with no anchor to a real moment. An aware datetime carries timezone information and unambiguously represents a single point in time. You cannot compare, subtract, or mix naive and aware datetimes — Python raises TypeError.

zoneinfo vs pytz

Featurezoneinfo (Python 3.9+)pytz (legacy)
Importfrom zoneinfo import ZoneInfoimport pytz
Create aware dtdatetime.now(ZoneInfo('US/Eastern'))datetime.now(pytz.timezone('US/Eastern'))
Convert tzdt.astimezone(ZoneInfo('Asia/Tokyo'))dt.astimezone(pytz.timezone('Asia/Tokyo'))
UTCfrom datetime import timezone; timezone.utcpytz.utc
InstallBuilt-in (3.9+)pip install pytz
RecommendationUse this for new projectsOnly for Python < 3.9

Common Patterns & Recipes

Parse dates from user input safely

Calculate age from birthdate

Find next weekday from today

Frequently Asked Questions

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

from datetime import datetime; now = datetime.now() gives you the local date and time. For UTC: datetime.now(timezone.utc). For just the date: from datetime import date; today = date.today(). These are all part of the standard library.

What is the difference between strftime and strptime?

strftime (string format time) converts a datetime to a string: dt.strftime('%Y-%m-%d') produces '2026-03-26'. strptime (string parse time) converts a string to a datetime: datetime.strptime('2026-03-26', '%Y-%m-%d'). The mnemonic: f = format (to string), p = parse (from string).

How do I add months to a date in Python?

The standard library's timedelta only supports days and seconds — not months or years, because months have variable lengths. Use dateutil.relativedelta: from dateutil.relativedelta import relativedelta; dt + relativedelta(months=3). Or with arrow: arrow.now().shift(months=3).

How do I handle timezones in Python?

Python 3.9+: use the built-in zoneinfo module. from zoneinfo import ZoneInfo; dt = datetime.now(ZoneInfo('America/New_York')). For older Python, use pytz. Always store datetimes as UTC internally and convert to local time only for display. Never use naive datetimes for anything that crosses timezone boundaries.

What is the difference between naive and aware datetimes?

A naive datetime has no timezone (tzinfo is None) — it's ambiguous. An aware datetime carries timezone information and represents an exact moment. Python won't let you compare or subtract naive and aware datetimes. Best practice: always create aware datetimes from the start using datetime.now(timezone.utc).

How do I convert a Unix timestamp to a datetime in Python?

datetime.fromtimestamp(ts) gives local time; datetime.fromtimestamp(ts, tz=timezone.utc) gives UTC. Going the other way: dt.timestamp() returns the Unix epoch as a float (Python 3.3+). For milliseconds, multiply or divide by 1000.

Related Tools