Dates in Python
? Working with Dates in Python
In Python, you can work with dates and times using the built-in datetime module. This module allows you to manipulate dates and times in both simple and complex ways.
? The datetime Module
The datetime module provides several classes for working with dates and times:
date: Used to represent a date (year, month, day).time: Used to represent a time (hours, minutes, seconds, and microseconds).datetime: Combines both date and time.timedelta: Represents the difference between twodatetimeobjects.tzinfo: Used to handle time zones.
? Getting the Current Date and Time
You can get the current date and time using the datetime.now() function.
Example: Get the current date and time
import datetime# Get the current date and timenow = datetime.datetime.now()print("Current date and time:", now)? Output:
Current date and time: 2025-04-01 14:30:00.123456? Creating Date and Time Objects
You can create custom datetime, date, or time objects by passing specific values.
1?? Creating a date Object
You can create a date object with a specific year, month, and day.
import datetime# Create a date objectd = datetime.date(2025, 4, 1)print(d) # Output: 2025-04-012?? Creating a time Object
You can create a time object with a specific hour, minute, second, and microsecond.
# Create a time objectt = datetime.time(14, 30, 0, 123456)print(t) # Output: 14:30:00.1234563?? Creating a datetime Object
A datetime object combines both date and time.
# Create a datetime objectdt = datetime.datetime(2025, 4, 1, 14, 30, 0)print(dt) # Output: 2025-04-01 14:30:00? Formatting Dates
You can format datetime objects into strings using the strftime() method.
Example: Format a datetime object
# Get the current date and timenow = datetime.datetime.now()# Format the current date and timeformatted = now.strftime("%Y-%m-%d %H:%M:%S")print(formatted) # Output: 2025-04-01 14:30:00Common format codes:
%Y: Year with century (e.g., 2025)%m: Month as a zero-padded decimal (01 to 12)%d: Day of the month (01 to 31)%H: Hour (24-hour clock, 00 to 23)%M: Minute (00 to 59)%S: Second (00 to 59)
? Parsing Strings into datetime Objects
You can convert a string representing a date and time into a datetime object using the strptime() method.
Example: Parse a date string into a datetime object
# Parse a string into a datetime objectdate_string = "2025-04-01 14:30:00"dt = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")print(dt) # Output: 2025-04-01 14:30:00? Working with Time Differences
You can calculate the difference between two datetime objects using the timedelta class.
Example: Calculate the difference between two datetime objects
# Create two datetime objectsdt1 = datetime.datetime(2025, 4, 1, 14, 30, 0)dt2 = datetime.datetime(2025, 4, 2, 16, 45, 0)# Calculate the differencedelta = dt2 - dt1print("Time difference:", delta)print("Days:", delta.days)print("Seconds:", delta.seconds)? Output:
Time difference: 1 day, 2:15:00Days: 1Seconds: 8100? Adding or Subtracting Time
You can add or subtract time using the timedelta class.
Example: Add 5 days to the current date
# Get the current date and timenow = datetime.datetime.now()# Add 5 daysdelta = datetime.timedelta(days=5)new_date = now + deltaprint("New date:", new_date)Example: Subtract 2 hours from the current time
# Subtract 2 hoursdelta = datetime.timedelta(hours=-2)new_time = now + deltaprint("New time:", new_time)? Working with Time Zones
Python also provides the pytz library for handling time zones. You can localize datetime objects to specific time zones.
import pytz# Get the current time in UTCutc_now = datetime.datetime.now(pytz.utc)# Convert to a different time zone (e.g., New York)new_york_time = utc_now.astimezone(pytz.timezone('America/New_York'))print("New York time:", new_york_time)? Summary
datetimemodule provides classes to work with dates and times.You can get the current date and time using
datetime.now().Use
datetime.date,datetime.time, anddatetime.datetimeto represent date, time, and both respectively.Format and parse strings using
strftime()andstrptime().Calculate time differences and add/subtract time using
timedelta.You can handle time zones with the
pytzlibrary.
Let me know if you need further details or examples! ?