📚Cheatsheets

Cheatsheet collection for go, rust, python, shell and javascript.

Python Datetime Operations

Common datetime operations in Python using the datetime module, with examples and outputs.

  1. Basic datetime operations (creating and accessing datetime objects)
  2. Formatting and parsing datetime strings
  3. Date arithmetic (adding/subtracting time, calculating differences)
  4. Comparing dates
  5. Working with timestamps
  6. Handling time zones (using the pytz library)

1. Basic Datetime Operations

from datetime import datetime, timedelta

# Get current date and time
now = datetime.now()
print(f"Current date and time: {now}")
# Output: Current date and time: 2024-07-04 13:01:23.456789

# Create a specific date
specific_date = datetime(2024, 12, 31, 23, 59, 59)
print(f"Specific date: {specific_date}")
# Output: Specific date: 2024-12-31 23:59:59

# Get date components
print(f"Year: {now.year}, Month: {now.month}, Day: {now.day}")
print(f"Hour: {now.hour}, Minute: {now.minute}, Second: {now.second}")
# Output: Year: 2024, Month: 7, Day: 4
# Output: Hour: 13, Minute: 1, Second: 23

2. Formatting and Parsing

# Format date as string
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted date: {formatted_date}")
# Output: Formatted date: 2024-07-04 13:01:23

# Parse string to datetime
date_string = "2024-12-31 23:59:59"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(f"Parsed date: {parsed_date}")
# Output: Parsed date: 2024-12-31 23:59:59

# ISO format
iso_date = now.isoformat()
print(f"ISO format: {iso_date}")
# Output: ISO format: 2024-07-04T13:01:23.456789

3. Date Arithmetic

# Add or subtract time
tomorrow = now + timedelta(days=1)
print(f"Tomorrow: {tomorrow}")
# Output: Tomorrow: 2024-07-05 13:01:23.456789

last_week = now - timedelta(weeks=1)
print(f"Last week: {last_week}")
# Output: Last week: 2024-06-27 13:01:23.456789

# Calculate time difference
time_difference = specific_date - now
print(f"Time until New Year: {time_difference}")
# Output: Time until New Year: 180 days, 10:58:36.543211

4. Comparing Dates

date1 = datetime(2024, 7, 4)
date2 = datetime(2024, 12, 31)

if date1 < date2:
    print("date1 is earlier than date2")
else:
    print("date1 is not earlier than date2")
# Output: date1 is earlier than date2

if date1 == now.replace(hour=0, minute=0, second=0, microsecond=0):
    print("date1 is today")
else:
    print("date1 is not today")
# Output: date1 is today

5. Working with Timestamps

# Get timestamp (seconds since epoch)
timestamp = datetime.timestamp(now)
print(f"Timestamp: {timestamp}")
# Output: Timestamp: 1720209683.456789

# Create datetime from timestamp
date_from_timestamp = datetime.fromtimestamp(timestamp)
print(f"Date from timestamp: {date_from_timestamp}")
# Output: Date from timestamp: 2024-07-04 13:01:23.456789

6. Working with Time Zones (requires pytz library)

from pytz import timezone

# Create a timezone-aware datetime
utc = timezone('UTC')
ny = timezone('America/New_York')
utc_now = utc.localize(datetime.now())
ny_now = utc_now.astimezone(ny)

print(f"UTC time: {utc_now}")
print(f"New York time: {ny_now}")
# Output: UTC time: 2024-07-04 13:01:23.456789+00:00
# Output: New York time: 2024-07-04 09:01:23.456789-04:00

# Convert between time zones
paris = timezone('Europe/Paris')
paris_now = ny_now.astimezone(paris)
print(f"Paris time: {paris_now}")
# Output: Paris time: 2024-07-04 15:01:23.456789+02:00