Python Date & Time

The Python Library provides the date & time module to work with dates and times.

example code:


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

datetime.dateRepresents a date (year, month, day)date(year, month, day)d = date(2022, 12, 31)
datetime.timeRepresents a time (hour, minute, second, microsecond)time(hour, minute, second, microsecond)t = time(12, 30, 45, 100000)
datetime.datetimeRepresents a date and timedatetime(year, month, day, hour, minute, second, microsecond)dt = datetime(2022, 12, 31, 12, 30, 45, 100000)
datetime.timedeltaRepresents a durationtimedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks)td = timedelta(days=7) the current = the current date and =
date.strftime(format)Formats the date according to the specified format stringdate.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 objectdatetime.strptime(string, format)dt = datetime.strptime("31/12/2022 12:30:45", "%d/%m/%Y %H:%M:%S")
timedelta + datetimeAdds a timedelta to a datetime to get a new datetimetimedelta + datetimenew_datetime = dt + td

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top