WE CODE NOW
  • Home 
  • Blog 
  • Guides 
Guides
  1. Home
  2. Guides
  3. Python Programming
  4. Handling Dates and Times in Python

Handling Dates and Times in Python

Posted on June 1, 2024  (Last modified on June 8, 2024) • 2 min read • 215 words
Python
 
Dates
 
Time
 
Datetime
 
Python
 
Dates
 
Time
 
Datetime
 
Share via
WE CODE NOW
Link copied to clipboard

Learn to handle dates and times in Python using the `datetime` module, including parsing, formatting, and performing arithmetic operations on dates.

On this page
  • Parsing and Formatting Dates
    • Parsing Dates
    • Formatting Dates
  • Working with Time
    • Current Date and Time
    • Specific Date and Time
  • Arithmetic Operations on Dates
    • Adding and Subtracting Dates
    • Difference Between Dates
  • Time Zones
    • Handling Time Zones
  • Conclusion

Handling Dates and Times in Python  

Managing dates and times is crucial for many applications. This guide covers the datetime module for parsing, formatting, and performing arithmetic operations on dates and times in Python.

Parsing and Formatting Dates  

Parsing Dates  

from datetime import datetime

date_str = "2024-06-14"
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
print(date_obj)  # Output: 2024-06-14 00:00:00

Formatting Dates  

formatted_date = date_obj.strftime("%B %d, %Y")
print(formatted_date)  # Output: June 14, 2024

Working with Time  

Current Date and Time  

now = datetime.now()
print(now)

Specific Date and Time  

specific_date = datetime(2024, 6, 14, 15, 30)
print(specific_date)

Arithmetic Operations on Dates  

Adding and Subtracting Dates  

from datetime import timedelta

tomorrow = now + timedelta(days=1)
print(tomorrow)

yesterday = now - timedelta(days=1)
print(yesterday)

Difference Between Dates  

difference = tomorrow - now
print(difference.days)  # Output: 1

Time Zones  

Handling Time Zones  

from datetime import timezone

utc_time = datetime.now(timezone.utc)
print(utc_time)

local_time = utc_time.astimezone()
print(local_time)

Time zones can be managed using third-party libraries like pytz.

from datetime import datetime
import pytz

utc = pytz.utc
est = pytz.timezone('US/Eastern')

utc_dt = datetime.now(utc)
est_dt = utc_dt.astimezone(est)
print(est_dt)

Conclusion  

Effective date and time management is essential for many applications. Practice using the datetime module to parse, format, and perform arithmetic operations on dates and times in Python.

 Python Regular Expressions (Regex)
Web Scraping with Python and BeautifulSoup 
On this page:
  • Parsing and Formatting Dates
    • Parsing Dates
    • Formatting Dates
  • Working with Time
    • Current Date and Time
    • Specific Date and Time
  • Arithmetic Operations on Dates
    • Adding and Subtracting Dates
    • Difference Between Dates
  • Time Zones
    • Handling Time Zones
  • Conclusion
Copyright © 2025 WE CODE NOW All rights reserved.
WE CODE NOW
Code copied to clipboard