Working with Dates and Time

📘 Python 👁 76 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

Working with Dates and Time in Python

Python provides the datetime and time modules to work with dates, times, and timestamps efficiently.


1. Importing the Modules

import datetime import time

2. Current Date and Time

from datetime import datetime now = datetime.now() print(now) # 2025-11-26 14:30:45.123456 print(now.date()) # 2025-11-26 print(now.time()) # 14:30:45.123456

3. Creating Specific Dates and Times

from datetime import date, time d = date(2025, 12, 31) t = time(15, 45, 30) print(d) # 2025-12-31 print(t) # 15:45:30

4. Formatting Dates and Times

  • Use strftime() to convert datetime objects to formatted strings.

  • Use strptime() to convert strings to datetime objects.

now = datetime.now() # Formatting print(now.strftime("%Y-%m-%d %H:%M:%S")) # 2025-11-26 14:30:45 print(now.strftime("%A, %B %d, %Y")) # Tuesday, November 26, 2025 # Parsing string to datetime date_str = "2025-12-31 23:59:59" dt_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S") print(dt_obj) # 2025-12-31 23:59:59

5. Date Arithmetic

  • Use timedelta for adding or subtracting days, hours, etc.

from datetime import timedelta today = datetime.now() tomorrow = today + timedelta(days=1) yesterday = today - timedelta(days=1) print(tomorrow) print(yesterday) # Adding hours or minutes future = today + timedelta(hours=5, minutes=30) print(future)

6. Working with Timestamps

  • Convert datetime to timestamp and back.

now = datetime.now() timestamp = now.timestamp() print(timestamp) # 1764355845.123456 dt_from_ts = datetime.fromtimestamp(timestamp) print(dt_from_ts) # 2025-11-26 14:30:45.123456

7. Time Module (Optional)

  • time.sleep(seconds) → pause execution

  • time.time() → current timestamp

  • time.localtime() → current local time tuple

  • time.gmtime() → current UTC time tuple

import time print(time.time()) # 1764355845.123456 time.sleep(2) # pauses for 2 seconds print(time.localtime())

8. Key Points

  • Use datetime for date and time objects.

  • Use timedelta for date arithmetic.

  • strftime formats datetime as string; strptime parses strings.

  • time module handles timestamps, delays, and low-level time operations.

  • Useful for scheduling, logging, and date calculations.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes