The python datetime library is a standard library package that comes with classes for manipulating or working with date and time.
In this 4 part guide we are going to look at the 4 basic classes this library comes with and how to work with them. These classes are
1.datetime.datetime
2.datetime.date
3.datetime.timedelta
4.datetime.time
PART ONE
datetime.datetime Class
a datetime is an object which consists of the combination of a date object and a time object.To create a datetime object:
#import datetime library
from datetime import datetime
#creating a datetime object
datetime_object = datetime(year,month,day,hour=0,minute=0,second=0,
microsecond=0,tzinfo=None)
# year : MINYEAR <= year <= MAXYEAR
# month: 1 <= month <= 12
# hour : 0 <= hour < 24,
# minute : 0 <= minute < 60
# second : 0 <= second < 60
# microsecond: 0 <= microsecond < 1000000
# if we wanted to create a datetime object for 1 January 1999
date = datetime(1999,1,1)
print(date)
result => 1999-01-01 00:00:00
Note
- hour,minute,second and microsecond are optional and default to zero
- Any argument outside the specified ranges raise a ValueError
This class has some useful methods too
datetime.now() : this returns the datetime object for the current moment.
time_now = datetime.now()
print(time_now)
result => 2024-05-21 15:49:17.632276
datetime.fromisoformat(): Return a datetime corresponding to a date_string in any valid ISO 8601 format, with the following exceptions.
date_string = "2024-05-21 15:49:17.632276"
result = datetime.fromisoformat(date_string)
print("Result Year": result.year)
print("Result Month": result.month)
=>Result Year : 2024
=>Result Month : 5
datetime.strptime(): Parses a string representation of a date/time and returns a datetime object.
date_string = "21/05/2024 15:49"
format_string = "%d/%m/%Y %H:%M"
parsed_date = datetime.strptime(date_string, format_string)
print(parsed_date)
result => 2024-05-21 15:49:00
datetime.strftime(): Parses a datetime object into a string given a specific format
now = datetime.now()
format_string = "%A, %d %B %Y %I:%M %p"
formatted_date = now.strftime(format_string)
print(formatted_date)
result => Tuesday, 21 May 2024 03:49 PM
for more information on the datetime formatting codes refer to w3 schools
Top comments (0)