Python Datetime
Python Datetime is a built-in module in Python programming language that allows developers to work with dates and times in a simple and efficient way. It provides a wide range of functionalities for handling date and time values, including parsing and formatting dates, performing arithmetic operations on dates and times, and working with time zones.
The module offers several classes and functions to work with datetime objects, date objects, time objects, and timedelta objects. With datetime objects, developers can easily perform operations such as calculating the difference between two dates or adding or subtracting days, months, or years from a given date. Date objects allow working with only dates without time information, and time objects allow working with only time information without dates. Timedelta objects are useful for measuring the difference between two dates or times in terms of days, hours, minutes, or seconds.
The Python Datetime module also includes timezone support, making it easy to work with date and time values across different time zones. Additionally, the module provides several formatting options for displaying date and time values in a way that is easy to read and understand.
Overall, the Python Datetime module is an essential tool for any developer working with date and time values in Python, providing a simple and flexible way to manipulate and work with dates and times.
In Python, you can output the date using the strftime()
method, which allows you to format the date and time in various ways.
Here’s an example:
import datetime # get the current date and time now = datetime.datetime.now() # output the date in various formats print(now.strftime("%Y-%m-%d")) # YYYY-MM-DD format print(now.strftime("%m/%d/%Y")) # MM/DD/YYYY format print(now.strftime("%d-%b-%Y")) # DD-MMM-YYYY format print(now.strftime("%A, %B %d, %Y")) # Weekday, Month Day, Year format
This code will output the current date in four different formats: YYYY-MM-DD, MM/DD/YYYY, DD-MMM-YYYY, and Weekday, Month Day, Year format.
You can customize the format string in the strftime() method to output the date in any format you want.
Here are some additional examples of how to output date using the strftime() method in Python:
import datetime # create a datetime object for a specific date my_date = datetime.datetime(2022, 12, 25) # output the date in various formats print(my_date.strftime("%Y-%m-%d")) # YYYY-MM-DD format print(my_date.strftime("%m/%d/%Y")) # MM/DD/YYYY format print(my_date.strftime("%d-%b-%Y")) # DD-MMM-YYYY format print(my_date.strftime("%A, %B %d, %Y")) # Weekday, Month Day, Year format # output the time in various formats print(my_date.strftime("%H:%M:%S")) # 24-hour format print(my_date.strftime("%I:%M:%S %p")) # 12-hour format with AM/PM # output the datetime in ISO format print(my_date.isoformat()) # ISO format
In this exampleample, we create a datetime
object for December 25, 2022, and use the strftime()
method to output the date in various formats. We also use the strftime()
method to output the time in different formats, including 24-hour format and 12-hour format with AM/PM.
Additionally, we output the datetime object in ISO format using the isoformat()
method. This method returns the date and time in ISO format, which is a standard format for representing date and time values in a machine-readable way.
import datetime # create a date object for today's date today = datetime.date.today() print(today) # create a date object for a specific date my_date = datetime.date(2022, 12, 25) print(my_date)
In this example, we import the datetime module and create a date object for today’s date using the date.today() method. We then print the today object to the console, which will output the date in the format YYYY-MM-DD.
We also create a date object for a specific date using the date() constructor and passing in the year, month, and day as arguments. We then print the my_date object to the console, which will output the date in the same format.
Note that the date object does not include any time information, only the year, month, and day. If you need to work with dates and times together, you can use the datetime object instead, which includes both date and time information.
Here are some additional examples of how to create date objects in Python:
import datetime # create a date object for tomorrow's date tomorrow = datetime.date.today() + datetime.timedelta(days=1) print(tomorrow) # create a date object for the first day of the current month first_day = datetime.date.today().replace(day=1) print(first_day) # create a date object for the last day of the current month last_day = datetime.date.today().replace(day=28) + datetime.timedelta(days=4) last_day = last_day - datetime.timedelta(days=last_day.day) print(last_day)
In the first example, we create a date object for tomorrow’s date by adding a timedelta object with one day to today’s date using the date.today() method.
In the second example, we create a date object for the first day of the current month using the replace() method to set the day of the month to 1.
In the third example, we create a date object for the last day of the current month by setting the day of the month to 28 (which is guaranteed to be before the last day of any month), adding a timedelta object with 4 days to handle leap years, and then subtracting the number of days equal to the day of the month using another timedelta object.
These are just a few examples of how to create date objects in Python. There are many other ways to create date objects based on specific requirements and use cases.
Here are a few more examples of how to create date objects in Python:
import datetime # create a date object from a string date_str = '2022-12-25' my_date = datetime.datetime.strptime(date_str, '%Y-%m-%d').date() print(my_date) # create a date object from a timestamp timestamp = 1647013729 my_date = datetime.date.fromtimestamp(timestamp) print(my_date) # create a date object for the current date and time in a specific timezone import pytz timezone = pytz.timezone('US/Eastern') my_date = datetime.datetime.now(timezone).date() print(my_date)
In the first example, we create a date object from a string representing a specific date using the strptime() method from the datetime module. We pass in the string and a format string that matches the format of the date string, and then call the date() method to extract only the date information.
In the second example, we create a date object from a Unix timestamp using the date.fromtimestamp() method from the datetime module. We pass in the timestamp as an argument, and the method returns a date object representing that date and time.
In the third example, we create a date object for the current date and time in a specific timezone using the datetime.now() method from the datetime module. We pass in a timezone object from the pytz module that represents the desired timezone, and then call the date() method to extract only the date information.
These examples demonstrate some additional ways to create date objects in Python based on specific requirements and use cases.
The strftime() Method
The strftime() method in Python is used to format datetime objects into strings according to a specified format. The strftime() method takes a single argument, which is a format string that specifies the format of the resulting string.
The format string can include various placeholders that represent different parts of the datetime object.
Here are some of the most commonly used placeholders:
%Y – 4-digit year
%m – 2-digit month (01-12)
%d – 2-digit day (01-31)
%H – 2-digit hour (00-23)
%M – 2-digit minute (00-59)
%S – 2-digit second (00-59)
%a – abbreviated weekday name (e.g. Mon)
%A – full weekday name (e.g. Monday)
%b – abbreviated month name (e.g. Jan)
%B – full month name (e.g. January)
Here’s an example that demonstrates how to use the strftime() method to format a datetime object into a string:
import datetime # create a datetime object for the current date and time now = datetime.datetime.now() # format the datetime object as a string date_string = now.strftime('%Y-%m-%d %H:%M:%S') # print the resulting string print(date_string)
In this example, we create a datetime object for the current date and time using the datetime.now() method from the datetime module. We then use the strftime() method to format the datetime object as a string in the format YYYY-MM-DD HH:MM:SS. Finally, we print the resulting string to the console.
The strftime() method is a powerful tool for formatting datetime objects into strings in a wide range of formats, making it a useful method for handling date and time information in Python.
Here are some additional examples of how to use the strftime() method in Python:
import datetime # create a datetime object for a specific date and time my_datetime = datetime.datetime(2022, 12, 25, 8, 30) # format the datetime object as a string date_string = my_datetime.strftime('%A, %B %d, %Y at %I:%M %p') # print the resulting string print(date_string)
In this example, we create a datetime object for a specific date and time (December 25th, 2022 at 8:30 AM) using the datetime.datetime() constructor. We then use the strftime() method to format the datetime object as a string in the format Weekday, Month DD, YYYY at HH:MM AM/PM, where Weekday is the full name of the day of the week, Month is the full name of the month, DD is the 2-digit day of the month, YYYY is the 4-digit year, HH is the 2-digit hour (12-hour clock), MM is the 2-digit minute, and AM/PM is either “AM” or “PM”. Finally, we print the resulting string to the console.
import datetime # create a datetime object for the current date and time now = datetime.datetime.now() # format the datetime object as a string using a custom format date_string = now.strftime('Today is %A, %B %d, %Y and the time is %I:%M %p.') # print the resulting string print(date_string)
In this example, we create a datetime object for the current date and time using the datetime.now() method. We then use the strftime() method to format the datetime object as a string in a custom format that includes a message (“Today is…and the time is…”). Finally, we print the resulting string to the console.
These are just a couple of examples of how to use the strftime() method to format datetime objects into strings in Python. The possibilities for formatting datetime objects with strftime() are nearly endless, and the method can be used to create strings in a wide variety of formats to suit specific needs and use cases.
here are some additional examples of how to use the strftime() method in Python:
import datetime # create a datetime object for a specific date and time my_datetime = datetime.datetime(2022, 12, 25, 8, 30) # format the datetime object as a string date_string = my_datetime.strftime('%A, %B %d, %Y at %I:%M %p') # print the resulting string print(date_string)
In this example, we create a datetime object for a specific date and time (December 25th, 2022 at 8:30 AM) using the datetime.datetime() constructor. We then use the strftime() method to format the datetime object as a string in the format Weekday, Month DD, YYYY at HH:MM AM/PM, where Weekday is the full name of the day of the week, Month is the full name of the month, DD is the 2-digit day of the month, YYYY is the 4-digit year, HH is the 2-digit hour (12-hour clock), MM is the 2-digit minute, and AM/PM is either “AM” or “PM”. Finally, we print the resulting string to the console.
import datetime # create a datetime object for the current date and time now = datetime.datetime.now() # format the datetime object as a string using a custom format date_string = now.strftime('Today is %A, %B %d, %Y and the time is %I:%M %p.') # print the resulting string print(date_string)
In this example, we create a datetime object for the current date and time using the datetime.now() method. We then use the strftime() method to format the datetime object as a string in a custom format that includes a message (“Today is…and the time is…”). Finally, we print the resulting string to the console.
These are just a couple of examples of how to use the strftime() method to format datetime objects into strings in Python. The possibilities for formatting datetime objects with strftime() are nearly endless, and the method can be used to create strings in a wide variety of formats to suit specific needs and use cases.
Reference of all the legal format codes
Here is a reference of all the legal format codes that can be used with the strftime() method in Python’s datetime module, along with examples:
Code Meaning Example
%a Abbreviated weekday name Mon
%A Full weekday name Monday
%b Abbreviated month name Jan
%B Full month name January
%c Local date and time representation Mon Jan 1 00:00:00 2000
%d Day of the month (zero-padded) 01
%e Day of the month (space-padded) 1
%f Microsecond (000000-999999) 000000
%F Shortcut for %Y-%m-%d 2000-01-01
%H Hour (24-hour clock, zero-padded) 00
%I Hour (12-hour clock, zero-padded) 12
%j Day of the year (zero-padded) 001
%m Month (zero-padded) 01
%M Minute (zero-padded) 00
%p AM/PM designation AM
%S Second (zero-padded) 00
%U Week number of the year (Sunday as the first day of the week) 00
%w Weekday as a decimal number (0-6, Sunday is 0) 1
%W Week number of the year (Monday as the first day of the week) 00
%x Local date representation 01/01/00
%X Local time representation 00:00:00
%y Year without century (zero-padded) 00
%Y Year with century 2000
%z UTC offset in the form ±HHMM[SS[.ffffff]] +0000
%Z Time zone name (empty string if the object is naive) UTC
%% Literal % character %
You can use any of these codes with the strftime() method to format datetime objects into strings in a wide variety of formats.
Here are some examples:
import datetime # create a datetime object for a specific date and time my_datetime = datetime.datetime(2000, 1, 1, 12, 30, 45) # format the datetime object using various codes print(my_datetime.strftime('%a, %b %d, %Y')) # Sat, Jan 01, 2000 print(my_datetime.strftime('%A, %B %d, %Y %H:%M:%S')) # Saturday, January 01, 2000 12:30:45 print(my_datetime.strftime('%m/%d/%y')) # 01/01/00 print(my_datetime.strftime('%H:%M:%S %p')) # 12:30:45 PM
These examples demonstrate how you can use various format codes to create different date and time formats.
Here are some more formats that you can use with the strftime() method:
Code Meaning Example
%C Century (first two digits of the year) 20
%D Shortcut for %m/%d/%y 01/01/00
%e Day of the month (space-padded) 1
%g Week-based year (last two digits) 99
%G Week-based year (four digits) 1999
%h Abbreviated month name (same as %b) Jan
%n Newline character
%o Day of the month (ordinal, e.g. “1st”, “2nd”, etc.) 1st
%r Time in AM/PM format 12:30:45 PM
%R Shortcut for %H:%M 12:30
%s Unix timestamp (seconds since 1970-01-01 00:00:00 UTC) 946684800
%t Tab character
%T Shortcut for %H:%M:%S 12:30:45
%u Weekday as a decimal number (1-7, Monday is 1) 6
%V Week number of the year (ISO 8601) 52
%W Week number of the year (Sunday as the first day of the week) 52
%x Local date representation (same as %D) 01/01/00
%X Local time representation (same as %T) 12:30:45
%Y Year with century (four digits) 2000
%z UTC offset in the form ±HHMM (no colon) +0000
%:z UTC offset in the form ±HH:MM +00:00
%::z UTC offset in the form ±HH:MM:SS +00:00:00
%#z UTC offset in the form ±HHMM[SS[.ffffff]] +0000
These formats allow you to create even more complex date and time formats using the strftime() method.
Here are some examples:
import datetime # create a datetime object for a specific date and time my_datetime = datetime.datetime(2000, 1, 1, 12, 30, 45) # format the datetime object using various codes print(my_datetime.strftime('%Y-%m-%d %H:%M:%S')) # 2000-01-01 12:30:45 print(my_datetime.strftime('%a %b %d %H:%M:%S %Z %Y')) # Sat Jan 01 12:30:45 UTC 2000 print(my_datetime.strftime('%c')) # Sat Jan 1 12:30:45 2000 print(my_datetime.strftime('%B %d, %Y is a %A')) # January 01, 2000 is a Saturday
These examples demonstrate how you can use a variety of formats to create different date and time formats. You can mix and match the different codes to create custom formats that suit your needs.
Here are some more code examples that demonstrate the use of strftime() method with different format codes:
import datetime # create a datetime object for a specific date and time my_datetime = datetime.datetime(2023, 3, 11, 15, 30, 0) # format the datetime object using various codes print(my_datetime.strftime('%Y/%m/%d')) # 2023/03/11 print(my_datetime.strftime('%B %d, %Y')) # March 11, 2023 print(my_datetime.strftime('%A %d %B %Y')) # Saturday 11 March 2023 print(my_datetime.strftime('%m/%d/%Y %H:%M:%S')) # 03/11/2023 15:30:00 print(my_datetime.strftime('%Y-%m-%d %I:%M %p')) # 2023-03-11 03:30 PM print(my_datetime.strftime('%c')) # Sat Mar 11 15:30:00 2023 print(my_datetime.strftime('%j')) # 070 print(my_datetime.strftime('%U')) # 10
Summary about python date:
In the first example, we create a date object for tomorrow’s date by adding a timedelta object with one day to today’s date using the date.today() method.
In the second example, we create a date object for the first day of the current month using the replace() method to set the day of the month to 1.
In the third example, we create a date object for the last day of the current month by setting the day of the month to 28 (which is guaranteed to be before the last day of any month), adding a timedelta object with 4 days to handle leap years, and then subtracting the number of days equal to the day of the month using another timedelta object.
These are just a few examples of how to create date objects in Python. There are many other ways to create date objects based on specific requirements and use cases.
Here are a few more examples of how to create date objects in Python:
import datetime # create a date object for today's date today = datetime.date.today() print(today) # output: 2023-03-11 # create a time object for the current time now = datetime.datetime.now().time() print(now) # output: 20:21:34.917936 # create a datetime object for a specific date and time my_datetime = datetime.datetime(2023, 3, 11, 20, 30, 0) print(my_datetime) # output: 2023-03-11 20:30:00 # calculate the difference between two dates date1 = datetime.date(2022, 1, 1) date2 = datetime.date(2023, 3, 11) difference = date2 - date1 print(difference.days) # output: 434 # format a date as a string using strftime() formatted_date = today.strftime('%B %d, %Y') print(formatted_date) # output: March 11, 2023 # format a time as a string using strftime() formatted_time = now.strftime('%I:%M %p') print(formatted_time) # output: 08:21 PM # format a datetime as a string using strftime() formatted_datetime = my_datetime.strftime('%Y-%m-%d %I:%M %p') print(formatted_datetime) # output: 2023-03-11 08:30 PM # create a timedelta object representing a duration of time one_day = datetime.timedelta(days=1) print(one_day) # output: 1 day, 0:00:00 # add a timedelta to a datetime object new_datetime = my_datetime + one_day print(new_datetime) # output: 2023-03-12 20:30:00
These examples demonstrate some of the basic operations you can perform with dates and times in Python, such as creating date and time objects, calculating differences between dates, formatting dates and times as strings, and working with timedelta objects to represent durations of time.
These methods can be used to perform a variety of operations, such as converting between date and time formats, working with time zones, and manipulating dates and times. By combining these methods with the ones previously mentioned, you can create complex programs that perform sophisticated date and time operations.
Here are some commonly used methods for working with date and time in Python:
date.today():
Returns the current local date.
date(year, month, day):
Returns a date object with the specified year, month, and day.
date.fromisoformat(date_string):
Returns a date object corresponding to a date string in ISO format (YYYY-MM-DD).
date.weekday():
Returns the day of the week as an integer (Monday is 0 and Sunday is 6).
date.isoweekday():
Returns the day of the week as an integer (Monday is 1 and Sunday is 7).
date.strftime(format):
Returns a string representing the date, formatted according to the specified format string.
datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
Returns a datetime object with the specified year, month, day, hour, minute, and second.
datetime.now():
Returns the current local date and time.
datetime.fromtimestamp(timestamp, tz=None):
Returns a datetime object corresponding to a POSIX timestamp (number of seconds since January 1, 1970, 00:00:00 UTC).
datetime.strptime(date_string, format):
Returns a datetime object corresponding to a date string, parsed according to the specified format string.
datetime.combine(date, time):
Returns a datetime object combining the date and time.
datetime.timestamp():
Returns the POSIX timestamp corresponding to the datetime object.
timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0): Returns a timedelta object representing a duration of time.
time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0):
Returns a time object with the specified hour, minute, and second.
time.fromisoformat(time_string):
Returns a time object corresponding to a time string in ISO format (HH:MM:SS.mmmmmm).
date.max:
Returns the maximum date value (9999-12-31).
date.min:
Returns the minimum date value (0001-01-01).
date.replace(year=self.year, month=self.month, day=self.day):
Returns a new date object with the specified year, month, and day.
date.timetuple():
Returns a time.struct_time object representing the date and time as a tuple.
date.toordinal():
Returns the proleptic Gregorian ordinal of the date (the number of days since January 1, 1 AD).
date.fromordinal(ordinal):
Returns a date object corresponding to a proleptic Gregorian ordinal.
datetime.date():
Returns the date portion of a datetime object.
datetime.time():
Returns the time portion of a datetime object.
datetime.astimezone(tz=None):
Returns a datetime object with the specified time zone.
datetime.utcoffset():
Returns the UTC offset of the datetime object.
datetime.dst():
Returns the daylight saving time adjustment of the datetime object.
datetime.replace(year=self.year, month=self.month, day=self.day, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0):
Returns a new datetime object with the specified attributes.
datetime.timetuple():
Returns a time.struct_time object representing the date and time as a tuple.
datetime.toordinal():
Returns the proleptic Gregorian ordinal of the date and time.
datetime.fromordinal(ordinal):
Returns a datetime object corresponding to a proleptic Gregorian ordinal.
here’s a list of all the methods available in Python’s datetime module along with an example for each one:
date(year, month, day): Creates a date object with the specified year, month, and day.
from datetime import date d = date(2022, 3, 11) print(d) # Output: 2022-03-11
date.today():
Returns a date object representing the current local date.
from datetime import date
today = date.today()
print(today) # Output: 2023-03-11
date.fromtimestamp(timestamp):
Creates a date object from a Unix timestamp
from datetime import date
timestamp = 1647000000
d = date.fromtimestamp(timestamp)
print(d) # Output: 2022-03-10
date.weekday(): Returns the day of the week as an integer (0 for Monday, 1 for Tuesday, etc.).
from datetime import date
d = date(2022, 3, 11)
weekday = d.weekday()
print(weekday) # Output: 4
date.isoweekday(): Returns the day of the week as an integer following the ISO standard (1 for Monday, 2 for Tuesday, etc.).
from datetime import date
d = date(2022, 3, 11)
weekday = d.isoweekday()
print(weekday) # Output: 5
date.isoformat(): Returns the date as an ISO formatted string (YYYY-MM-DD).
from datetime import date
d = date(2022, 3, 11)
iso_date = d.isoformat()
print(iso_date) # Output: 2022-03-11
date.strftime(format): Returns the date as a string formatted according to the specified format.
from datetime import date
d = date(2022, 3, 11)
formatted_date = d.strftime(‘%d/%m/%Y’)
print(formatted_date) # Output: 11/03/2022
date.replace(year=self.year, month=self.month, day=self.day): Returns a new date object with the specified year, month, and day.
from datetime import date
d = date(2022, 3, 11)
new_d = d.replace(year=2023, month=3, day=11)
print(new_d) # Output: 2023-03-11
date.timetuple(): Returns a time.struct_time object representing the date and time as a tuple.
from datetime import date
d = date(2022, 3, 11)
timetuple = d.timetuple()
print(timetuple) # Output: time.struct_time(tm_year=2022, tm_mon=3, tm_mday=11, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=70, tm_isdst=-1)
date.toordinal(): Returns the proleptic Gregorian ordinal of the date (the number of days since January 1, 1 AD).
from datetime import date
d = date(2022, 3, 11)
ordinal = d.toordinal()
print(ordinal) # Output: 737
date.fromordinal(ordinal): Returns a date object corresponding to the proleptic Gregorian ordinal.
from datetime import date
ordinal = 737
d = date.fromordinal(ordinal)
print(d) # Output: 0002-03-07
date.fromisoformat(date_string): Creates a date object from an ISO formatted string.
from datetime import date
date_string = ‘2022-03-11’
d = date.fromisoformat(date_string)
print(d) # Output: 2022-03-11
date.min: Returns the earliest possible date, date(MINYEAR, 1, 1).
from datetime import date
min_date = date.min
print(min_date) # Output: 0001-01-01
date.max: Returns the latest possible date, date(MAXYEAR, 12, 31).
from datetime import date
max_date = date.max
print(max_date) # Output: 9999-12-31
date.resolution: The smallest possible difference between non-equal dates, timedelta(days=1).
from datetime import date
resolution = date.resolution
print(resolution) # Output: 1 day, 0:00:00
time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0): Creates a time object with the specified hour, minute, second, and microsecond.
from datetime import time
t = time(14, 30, 0)
print(t) # Output: 14:30:00
time.min: Returns the earliest possible time, time(0, 0, 0, 0).
from datetime import time
min_time = time.min
print(min_time) # Output: 00:00:00
time.max: Returns the latest possible time, time(23, 59, 59, 999999).
from datetime import time
max_time = time.max
print(max_time) # Output: 23:59:59.999999
time.resolution: The smallest possible difference between non-equal times, timedelta(microseconds=1).
from datetime import time
resolution = time.resolution
print(resolution) # Output: 0:00:00.000001
datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0): Creates a datetime object with the specified year, month, day, hour, minute, second, and microsecond.
from datetime import datetime
dt = datetime(2022, 3, 11, 14, 30, 0)
print(dt) # Output: 2022-03-11 14:30:00
datetime.today(): Returns a datetime object representing the current local date and time.
from datetime import datetime
today = datetime.today()
print(today) # Output: 2023-03-11 00:00:00.000000
22.datetime.now(tz=None)
The datetime.now(tz=None) method returns the current date and time in the local time zone. The optional tz argument allows you to specify a time zone for the result. Here are some examples of how you can use this method:
from datetime import datetime
now = datetime.now()
print(now) # Output: 2023-03-11 14:53:29.872837
datetime.utcnow(): Returns a datetime object representing the current UTC date and time
from datetime import datetime
utc_now = datetime.utcnow()
print(utc_now) # Output: 2023-03-11 08:10:00.000000
datetime.fromtimestamp(timestamp, tz=None): Creates a datetime object from a POSIX timestamp (the number of seconds since January 1, 1970, 00:00:00 UTC).
from datetime import datetime
timestamp = 1646995800
dt = datetime.fromtimestamp(timestamp)
print(dt) # Output: 2022-03-10 08:10:00
datetime.fromordinal(ordinal): Returns a datetime object corresponding to the proleptic Gregorian ordinal.
from datetime import datetime
ordinal = 737
dt = datetime.fromordinal(ordinal)
print(dt) # Output: 0002-03-07 00:00:00
datetime.fromisoformat(date_string): Creates a datetime object from an ISO formatted string.
from datetime import datetime
date_string = ‘2022-03-11T14:30:00’
dt = datetime.fromisoformat(date_string)
print(dt) # Output: 2022-03-11 14:30:00
datetime.strptime(date_string, format): Parses a string representing a date and time and returns a datetime object.
from datetime import datetime
date_string = ‘2022-03-11 14:30:00’
format = ‘%Y-%m-%d %H:%M:%S’
dt = datetime.strptime(date_string, format)
print(dt) # Output: 2022-03-11 14:30:00
datetime.min: Returns the earliest possible datetime, datetime(MINYEAR, 1, 1, tzinfo=None).
from datetime import datetime
min_datetime = datetime.min
print(min_datetime) # Output: 0001-01-01 00:00:00
datetime.max: Returns the latest possible datetime, datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=None).
from datetime import datetime
max_datetime = datetime.max
print(max_datetime) # Output: 9999-12-31 23:59:59.999999
datetime.resolution: The smallest possible difference between non-equal datetimes, timedelta(microseconds=1).
from datetime import datetime
resolution = datetime.resolution
print(resolution) # Output: 0:00:00.000001
timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0): Represents a duration, the difference between two dates or times
from datetime import timedelta
# Create a timedelta object representing 1 day
one_day = timedelta(days=1)
print(one_day) # Output: 1 day, 0:00:00
%W b) %U c) %w d) %y Answer: a) %W
Quiz
1-Which Python module provides classes for working with date and time values? a) math b) datetime c) time d) calendar Answer: b) datetime
2-Which class in the datetime module represents a date (year, month, and day)? a) date b) time c) datetime d) timedelta Answer: a) date
3-Which method allows you to create a date object for today’s date? a) date.today() b) datetime.now() c) time.now() d) date.fromtimestamp() Answer: a) date.today()
4-Which class in the datetime module represents a duration of time? a) date b) time c) datetime d) timedelta Answer: d) timedelta
5-Which method allows you to format a date or time value as a string using a variety of format codes?
a) strftime() b) strptime() c) format() d) toString() Answer: a) strftime()
6-Which format code represents the full name of the month (e.g. “January”, “February”, etc.)?
a) %m b) %b c) %B d) %a Answer: c) %B
7-Which format code represents the 24-hour time (e.g. “13:00”, “14:30”, etc.)?
a) %I:%M %p b) %H:%M c) %m/%d/%Y d) %A, %B %d, %Y Answer: b) %H:%M
8-Which method allows you to add a duration of time to a datetime object?
a) datetime.add() b) datetime.add_timedelta() c) datetime.timedelta() d) datetime + timedelta Answer: d) datetime + timedelta
9-Which method returns the day of the week as an integer (0 for Monday, 1 for Tuesday, etc.) for a date object?
a) date.weekday() b) date.dayofweek() c) date.get_weekday() d) date.day() Answer: a) date.weekday()
10-Which method allows you to create a time object for a specific hour, minute, and second? a) time.now() b) time.fromisoformat() c) time(hour, minute, second) d) time.strftime() Answer: c) time(hour, minute, second)
11-Which method allows you to parse a string representing a date or time value into a datetime object?
a) datetime.strptime() b) datetime.format() c) datetime.parse() d) datetime.fromisoformat() Answer: a) datetime.strptime()
Which format code represents the day of the month as a zero-padded decimal number (e.g. “01”, “02”, etc.)? a) %m b) %d c) %D d) %j Answer: b) %d
12-Which method allows you to create a datetime object for a specific year, month, day, hour, minute, and second?
a) datetime.now() b) datetime.combine() c) datetime.datetime() d) datetime.fromisoformat() Answer: c) datetime.datetime()
13-Which method allows you to subtract two datetime objects to get a timedelta object representing the duration between them?
a) datetime.subtract() b) datetime – datetime c) datetime.timedelta() d) datetime.duration() Answer: b) datetime – datetime
14-Which format code represents the day of the week as a full name (e.g. “Monday”, “Tuesday”, etc.)?
a) %w b) %a c) %A d) %U Answer: c) %A
15-Which method allows you to create a date object for a specific year, month, and day?
a) date.today() b) date.fromtimestamp() c) date(year, month, day) d) date.fromisoformat() Answer: c) date(year, month, day)
16-Which method allows you to create a time object for the current time (hour, minute, and second)?
a) time.now() b) time.fromisoformat() c) time(hour, minute, second) d) time.strftime() Answer: a) time.now()
17-Which format code represents the hour (12-hour clock) as a zero-padded decimal number (e.g. “01”, “02”, etc.)?
a) %I b) %H c) %M d) %p Answer: a) %I
18-Which method allows you to create a timedelta object representing a duration of time specified in days, hours, minutes, and seconds?
a) timedelta.fromisoformat()
b) timedelta.total_seconds()
c) timedelta(days, hours, minutes, seconds)
d) timedelta.combine()
Answer: c) timedelta(days, hours, minutes, seconds)
19-Which format code represents the year as a zero-padded decimal number (e.g. “2022”)?
a) %Y b) %y c) %j d) %m
Answer: a) %Y
20-Which method allows you to convert a date object to a string in a specified format?
a) date.strftime() b) date.tostring() c) date.format() d) date.stringify()
Answer: a) date.strftime()
21-Which format code represents the hour (24-hour clock) as a zero-padded decimal number (e.g. “01”, “02”, etc.)?
a) %I b) %H c) %M d) %p
Answer: b) %H
22-Which method allows you to add a timedelta object to a datetime object to get a new datetime object with the adjusted date and time?
a) datetime.add() b) datetime.timedelta() c) datetime + timedelta d) datetime.adjust()
Answer: c) datetime + timedelta
23-Which format code represents the minute as a zero-padded decimal number (e.g. “01”, “02”, etc.)?
a) %m b) %M c) %S d) %T
Answer: b) %M
24-Which method allows you to create a time object for a specific hour, minute, and second?
a) time.fromisoformat() b) time.combine() c) time(hour, minute, second) d) time.now()
Answer: c) time(hour, minute, second)
25-Which format code represents the second as a zero-padded decimal number (e.g. “01”, “02”, etc.)? a) %s b) %S c) %h d) %H Answer: b) %S
26-Which method allows you to convert a datetime object to a Unix timestamp (number of seconds since January 1, 1970, 00:00:00 UTC)?
a) datetime.timestamp() b) datetime.to_unix() c) datetime.to_timestamp() d) datetime.unixtime() Answer: a) datetime.timestamp()
27-Which format code represents the AM/PM designation (e.g. “AM” or “PM”)?
a) %a b) %A c) %p d) %P
Answer: c) %p
28-Which method allows you to create a date object for the current date?
a) date.today() b) date.now() c) date.fromtimestamp() d) date.fromisoformat()
Answer: a) date.today()