🕐 Getting Current Date and Time

Getting the current date and time is one of the most common operations in programming. Python's datetime module provides several ways to retrieve current temporal information, whether you need just the date, just the time, or both together.

from datetime import datetime, date, time

# Get current date and time
now = datetime.now()
today = date.today()

print(f"Current datetime: {now}")
print(f"Today's date: {today}")
print(f"Current time: {now.time()}")

🎯 Different Ways to Get Current Time

Python offers multiple methods to get current temporal information depending on your needs.

Current Date and Time

from datetime import datetime

# Get current local date and time
now = datetime.now()
print(f"Now: {now}")

# Get specific components
print(f"Year: {now.year}")
print(f"Month: {now.month}")
print(f"Day: {now.day}")
print(f"Hour: {now.hour}")
print(f"Minute: {now.minute}")
print(f"Second: {now.second}")

Current Date Only

from datetime import date

# Get current date
today = date.today()
print(f"Today: {today}")

# Get date components
print(f"Year: {today.year}")
print(f"Month: {today.month}")
print(f"Day: {today.day}")

# Get weekday (0=Monday, 6=Sunday)
print(f"Weekday: {today.weekday()}")
print(f"Day name: {today.strftime('%A')}")

Current Time Only

from datetime import datetime

# Get current time from datetime
now = datetime.now()
current_time = now.time()

print(f"Current time: {current_time}")
print(f"Hour: {current_time.hour}")
print(f"Minute: {current_time.minute}")
print(f"Second: {current_time.second}")
print(f"Microsecond: {current_time.microsecond}")

🌍 UTC vs Local Time

Understanding the difference between local time and UTC is crucial for applications.

UTC Time

from datetime import datetime

# Get UTC time
utc_now = datetime.utcnow()
local_now = datetime.now()

print(f"UTC time: {utc_now}")
print(f"Local time: {local_now}")

# Calculate time zone offset
offset = local_now - utc_now
print(f"Time zone offset: {offset}")

Timestamp Operations

import time
from datetime import datetime

# Get Unix timestamp (seconds since 1970-01-01)
timestamp = time.time()
print(f"Unix timestamp: {timestamp}")

# Convert timestamp to datetime
dt = datetime.fromtimestamp(timestamp)
print(f"From timestamp: {dt}")

# Get timestamp from datetime
dt_timestamp = datetime.now().timestamp()
print(f"DateTime timestamp: {dt_timestamp}")

📅 Practical Examples

Let's see how to use current date/time in real applications.

Logging and Timestamps

from datetime import datetime

def log_event(message):
    """Simple logging with timestamp"""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print(f"[{timestamp}] {message}")

# Example usage
log_event("Application started")
log_event("User logged in")
log_event("Processing data")
log_event("Operation completed")

File Naming with Dates

from datetime import datetime

def create_filename(base_name, extension="txt"):
    """Create filename with current date/time"""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    return f"{base_name}_{timestamp}.{extension}"

# Example usage
log_file = create_filename("application_log", "log")
backup_file = create_filename("data_backup", "json")
report_file = create_filename("daily_report", "pdf")

print(f"Log file: {log_file}")
print(f"Backup file: {backup_file}")
print(f"Report file: {report_file}")

Age Calculation

from datetime import date

def calculate_age(birth_date):
    """Calculate age from birth date"""
    today = date.today()
    
    # Calculate age
    age = today.year - birth_date.year
    
    # Adjust if birthday hasn't occurred this year
    if today.month < birth_date.month or (
        today.month == birth_date.month and today.day < birth_date.day
    ):
        age -= 1
    
    return age

# Example usage
birth = date(1990, 5, 15)
age = calculate_age(birth)
print(f"Age: {age} years old")

# Days until next birthday
next_birthday = date(2024, 5, 15)  # Replace with current year
days_to_birthday = (next_birthday - date.today()).days
print(f"Days to next birthday: {days_to_birthday}")

📊 Time Methods Reference

MethodReturnsUse CaseExample
datetime.now()Local datetimeGeneral timestamps2024-03-15 14:30:45
date.today()Current dateDaily operations2024-03-15
datetime.utcnow()UTC datetimeGlobal applications2024-03-15 19:30:45
time.time()Unix timestampPerformance timing1710519045.123
datetime.fromtimestamp()DateTime from timestampConvert timestampsConvert 1710519045

🎯 Key Takeaways

🚀 What's Next?

Now that you can get current dates and times, learn how to format them for display and user interfaces.

Continue to: Format Dates

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent