datetime Cheat Sheet

Here’s a cheat sheet for working with datetime in Python:

Importing datetime Module

from datetime import datetime, date, time, timedelta

Current Date and Time

now = datetime.now()
current_date = date.today()
current_time = datetime.now().time()

Creating a Specific Date and Time

specific_date = date(2022, 12, 31)
specific_time = time(12, 30, 0)
specific_datetime = datetime(2022, 12, 31, 12, 30, 0)

Formatting Datetime

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

Parsing Strings to Datetime

date_string = "2023-12-20"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d")

Arithmetic Operations

future_date = now + timedelta(days=7)
past_date = now - timedelta(weeks=2)

Extracting Components

year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second

Comparing Datetimes

is_future = future_date > now
is_past = past_date < now

Difference Between Datetimes

time_difference = future_date - now
days_difference = time_difference.days

Working with Timezones

from pytz import timezone

utc_now = datetime.now(timezone('UTC'))
local_now = utc_now.astimezone(timezone('America/New_York'))

Handling Timezones with pytz

import pytz

utc = pytz.UTC
est = pytz.timezone('America/New_York')

utc_now = datetime.now(utc)
est_now = datetime.now(est)

Check if a Year is a Leap Year

is_leap_year = calendar.isleap(year)

Common Date Operations

# Get the day of the week (0 = Monday, 6 = Sunday)
day_of_week = now.weekday()

# Check if it's a leap year
is_leap_year = calendar.isleap(now.year)

# Get the number of days in a month
days_in_month = calendar.monthrange(now.year, now.month)[1]

Converting Timestamp to Datetime

timestamp = 1641067200
dt_from_timestamp = datetime.utcfromtimestamp(timestamp)

This cheat sheet covers various aspects of working with datetime in Python. Adjust and expand based on your specific needs and use cases.