The Python Library provides the date & time
module to work with dates and times.
example code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
from datetime import datetime, timedelta # A tuple to store information about a car's manufacturing date manufacturing_date = (2020, 12, 31) # Creating a datetime object from the manufacturing date dt = datetime(*manufacturing_date) # Calculating the current date and time now = datetime.now() # Calculating the duration between the manufacturing date and the current date duration = now - dt # Printing the duration in days, seconds, and microseconds print(f"Duration in days: {duration.days}") print(f"Duration in seconds: {duration.seconds}") print(f"Duration in microseconds: {duration.microseconds}") # Adding a year to the manufacturing date new_manufacturing_date = dt + timedelta(days=365) print(f"New manufacturing date: {new_manufacturing_date}") # Formatting the manufacturing date in a specific format formatted_date = dt.strftime("%B %d, %Y") print(f"Formatted manufacturing date: {formatted_date}") |
Output:
Duration in days: 669
Duration in seconds: 48167
Duration in microseconds: 995000
New manufacturing date: 2021-12-31 00:00:00
Formatted manufacturing date: December 31, 2020
Common Date and Time methods
Method | Description | Syntax | Example |
---|---|---|---|
datetime.date | Represents a date (year, month, day) | date(year, month, day) | d = date(2022, 12, 31) |
datetime.time | Represents a time (hour, minute, second, microsecond) | time(hour, minute, second, microsecond) | t = time(12, 30, 45, 100000) |
datetime.datetime | Represents a date and time | datetime(year, month, day, hour, minute, second, microsecond) | dt = datetime(2022, 12, 31, 12, 30, 45, 100000) |
datetime.timedelta | Represents a duration | timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks) | td = timedelta(days=7) |
date.today() | Returns the current date | date.today() | today = date.today() |
datetime.now() | Returns the current date and time | datetime.now() | now = datetime.now() |
date.strftime(format) | Formats the date according to the specified format string | date.strftime(format) | formatted_date = d.strftime("%B %d, %Y") |
datetime.strptime(string, format) | Parses a string representation of a date and time and returns a datetime object | datetime.strptime(string, format) | dt = datetime.strptime("31/12/2022 12:30:45", "%d/%m/%Y %H:%M:%S") |
timedelta + datetime | Adds a timedelta to a datetime to get a new datetime | timedelta + datetime | new_datetime = dt + td |