Python datetime, date, time, timedelta Example, How to create a timezone aware datetime object

Python datetime


The datetime module in Python provides classes to work with dates and times. In this tutorial, we'll cover some of the most commonly used classes and methods in the datetime module.

  • datetime.date class:

The date class represents a date (year, month, and day). Here's how to create a date object and access its attributes:

from datetime import date # Create a date object d = date(2023, 5, 1) # Access date attributes print(d.year) # Output: 2023 print(d.month) # Output: 5 print(d.day) # Output: 1 

To get the current date, use the date.today() method:

from datetime import date # Get the current date current_date = date.today() print(current_date) 
  • datetime.time class:

The time class represents a time of day (hour, minute, second, microsecond). Here's how to create a time object and access its attributes:

from datetime import time # Create a time object t = time(14, 30, 45) # Access time attributes print(t.hour) # Output: 14 print(t.minute) # Output: 30 print(t.second) # Output: 45 
  • datetime.datetime class:

The datetime class represents both date and time. Here's how to create a datetime object and access its attributes:

from datetime import datetime # Create a datetime object dt = datetime(2023, 5, 1, 14, 30, 45) # Access datetime attributes print(dt.year) # Output: 2023 print(dt.month) # Output: 5 print(dt.day) # Output: 1 print(dt.hour) # Output: 14 print(dt.minute) # Output: 30 print(dt.second) # Output: 45 

To get the current date and time, use the datetime.now() method:

from datetime import datetime # Get the current date and time current_datetime = datetime.now() print(current_datetime) 
  • datetime.timedelta class:

The timedelta class represents a duration or difference between two dates or times. Here's how to create a timedelta object and perform arithmetic operations with dates and times:

from datetime import datetime, timedelta # Create datetime objects dt1 = datetime(2023, 5, 1, 14, 30, 45) dt2 = datetime(2023, 5, 10, 16, 45, 30) # Calculate the difference between two datetimes diff = dt2 - dt1 print(diff) # Output: 9 days, 2:14:45 # Add a duration to a datetime duration = timedelta(days=7, hours=3) new_dt = dt1 + duration print(new_dt) # Output: 2023-05-08 17:30:45 

Examples

  1. Working with dates in Python using datetime:

    • Description: The datetime module provides classes for working with dates and times in Python.
    • Code:
    from datetime import datetime # Current date and time current_datetime = datetime.now() 
  2. Creating datetime objects in Python:

    • Description: datetime objects can be created by specifying the year, month, day, hour, minute, and second.
    • Code:
    from datetime import datetime # Creating a datetime object specific_datetime = datetime(2023, 1, 15, 12, 30, 0) 
  3. Formatting and parsing dates with datetime in Python:

    • Description: strftime is used to format datetime objects into strings, and strptime is used for parsing strings into datetime objects.
    • Code:
    from datetime import datetime # Formatting datetime formatted_date = current_datetime.strftime('%Y-%m-%d %H:%M:%S') # Parsing string to datetime parsed_datetime = datetime.strptime('2023-01-15 12:30:00', '%Y-%m-%d %H:%M:%S') 
  4. Performing arithmetic operations with datetime objects:

    • Description: datetime objects support arithmetic operations for calculating durations.
    • Code:
    from datetime import datetime, timedelta # Adding days to a datetime object future_date = current_datetime + timedelta(days=7) 
  5. Dealing with time zones in Python datetime:

    • Description: Use the pytz library to work with time zones in datetime.
    • Code:
    from datetime import datetime import pytz # Creating a datetime object with time zone tz = pytz.timezone('America/New_York') localized_datetime = datetime.now(tz) 
  6. Handling timedelta for date and time differences in Python:

    • Description: timedelta represents the difference between two dates or times.
    • Code:
    from datetime import datetime, timedelta # Creating a timedelta object time_difference = future_date - current_datetime 
  7. Converting between datetime and string in Python:

    • Description: Convert datetime objects to strings and vice versa.
    • Code:
    from datetime import datetime # Converting datetime to string date_string = current_datetime.strftime('%Y-%m-%d %H:%M:%S') # Converting string to datetime converted_datetime = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S') 
  8. Using datetime with file I/O in Python:

    • Description: Store and retrieve datetime objects in/from files.
    • Code:
    from datetime import datetime # Writing datetime to a file with open('timestamp.txt', 'w') as file: file.write(current_datetime.strftime('%Y-%m-%d %H:%M:%S')) # Reading datetime from a file with open('timestamp.txt', 'r') as file: stored_datetime = datetime.strptime(file.read(), '%Y-%m-%d %H:%M:%S') 

More Tags

handbrake mailto functional-dependencies http-post sqlxml auto carousel stubbing drupal ohhttpstubs

More Programming Guides

Other Guides

More Programming Examples


More Python Basic Tutorials


Popular Tutorials for Python Flow Control


Popular Tutorials for Python Functions


Popular Tutorials for Python Data Types


Popular Tutorials for Python Date and Time


Popular Tutorials for Python Files


Popular Tutorials for Python String


Popular Tutorials for Python List


Popular Tutorials for Python Dictionary


Popular Tutorials for Python Variable


Popular Tutorials for Python Input/Output


Popular Tutorials for Python Exceptions


More Python Advanced Tutorials