Limited Offer
60% OFF on all plans!

Date & Time in Python

Complete guide to Python Date & Time: datetime module, timestamps, parsing, formatting, comparison, arithmetic, timezone handling, UTC vs local time, and backend best practices.

Introduction to Date & Time

Python handles date and time using the built-in datetime module. Internally, timestamps are represented as seconds since the Unix Epoch (1 Jan 1970 UTC).

1. What is datetime?

datetime is a class inside the datetime module.

Creating Date & Time Objects

Python allows creating datetime objects using current time, components, timestamps, and parsing strings.

1. Current Date & Time

Using now() and today().

2. Create from Components

Year, month, day, hour, minute.

3. From Timestamp

Seconds since epoch.

4. Parse from String

Using strptime.

Working with Timestamps

Timestamps are commonly used in APIs and databases.

1. Current Timestamp

Using timestamp().

Getting Date Components

datetime object exposes attributes for year, month, etc.

1. Access Components

Using attributes.

Formatting Date & Time

strftime formats datetime into readable strings.

1. Using strftime

Custom formatting.

Comparing Dates

Datetime objects support comparison operators.

1. Comparing Two Dates

Using <, >, ==.

Date Arithmetic

timedelta is used for date arithmetic.

1. Adding / Subtracting Days

Using timedelta.

2. Difference Between Dates

Subtract two datetime objects.

Timezones & UTC

Naive datetime objects do not contain timezone information. Use timezone.utc for consistent backend systems.

1. Get Current UTC Time

Using timezone.utc.

Best Practices

Date & time handling is error-prone. Follow these rules.

1. Recommended Practices

Rules to follow.