Unlike other programming languages, Python doesn’t allow us to work with Date objects directly. To work with date and time objects, you have to import a module called datetime in Python. This Python datetime module holds different classes to work with dates or to manipulate dates and times.
To import the datetime module in Python.
import datetime
The syntax of this Python datetime is
datetime.datetime(Year_Number, Month_Number, Day_Number, Hours, Minutes, Seconds)
Learn how to import datetime in Python, work with date and time objects, format datetime, timedelta with practical examples.
Python datetime examples
Let me show you the list of available methods in this Python datetime module. For this, you have to use datetime as the dir function argument.
# datetime Example import datetime print(dir(datetime))
The MAXYEAR returns the maximum(highest) year supported by the datetime module, i.e., 9999. The MINYEAR returns the smallest allowed year, i.e., 1.
import datetime print('Maximum Year = ', datetime.MAXYEAR) print('Minimum Year = ', datetime.MINYEAR)
The following datetime example uses the Python today method to returns the current date.
import datetime dt = datetime.date.today() print('Today\'s Date = ', dt)
Python datetime class
This class has attributes of year, month, and day. Here, the first print statement extracts and returns the Year from the current date. The next two print statement returns Month number and Day.
import datetime today = datetime.date.today() print('Today\'s Date = ', today) print('Year from Today\'s Date = ', today.year) print('Month from Today\'s Date = ', today.month) print('Day from Today\'s Date = ', today.day)
Python datetime now
The datetime module has now function, which returns the current date and time.
import datetime dt = datetime.datetime.now() print(dt) print('Today\'s Date and Time = ', dt)
Until now, we are using the import datetime, and that was the reason we are using datetim.datetime.method_name. However, if we use from datetime import datetime, we can get rid of that extra datetime.
See the available date and time functions in Python datetime to extract and return date, time from the current date & time.
from datetime import datetime dt = datetime.now() print('Date and time = ', dt) print('Current Date = ', dt.date()) print('Current Time = ', dt.time())
Python datetime class attributes
It returns the Year from the current date and time.
import datetime dt = datetime.datetime.now() print('Today\'s Date and Time = ', dt) print('Calendar Year = ', dt.year)
This example displays the list of all the available attributes in Python datetime class. They are Year, Month, Day of Month, hour, minute, second, microsecond, and weekday.
from datetime import datetime dt = datetime.now() print('Date = ', dt) print('Year from Date = ', dt.year) print('Month from Date = ', dt.month) print('Day from Date = ', dt.day) print('Hour from Date = ', dt.hour) print('Minute from Date = ', dt.minute) print('Second from Date = ', dt.second) print('Microsecond from Date = ', dt.microsecond) print('Weekday Number from Date = ', dt.weekday())
The Python datetime module has the time class used to work or manipulate time values. Here, we used the time class to write the time from the current date and time. Next, we used the print statement to return the time parts using the available attributes hour, minute, second, and microsecond.
from datetime import datetime time = datetime.time(datetime.now()) print('Current Time = ', time) print('Hour from Current Time = ', time.hour) print('Minute from Current Time = ', time.minute) print('Second from Current Time = ', time.second) print('Microsecond from Current Time = ', time.microsecond)
Python isoformat
The Python datetime class has the isoformat, which returns a string representation of a date in ISO 8601 format of YYYY-MM-DD
from datetime import datetime print(datetime.now()) print(datetime.now().isoformat())
In all our previous datetime examples, we are working with the current date and time using now or today. However, you can use the date function to create a custom date. Here, we are using the custom date and returning it in iso format.
from datetime import date dt = date(2018, 1, 31) print(dt) print(dt.isoformat())
Create Date and Time using Python datetime module
Using the datetime function to create a custom date. This function accepts year, month, day, hour, minute, second, and microsecond. Here, we used the first three to create a custom date
from datetime import datetime dt = datetime(2017, 12, 31) print('Date and Time = ', dt)
It is another example to create a custom date using the datetime function.
import datetime dt = datetime.datetime(2018, 12, 31) print('Date and Time = ', dt) dte = datetime.date(2018, 12, 31) print('Date = ', dte)
The first statement creates a custom date and time with zero hours. The second one creates a custom date and time, and the third one creates a custom date and time along with microseconds.
from datetime import datetime dt = datetime(2014, 12, 31) print('Date and Time = ', dt) dt2 = datetime(2014, 12, 31, 22, 33, 44) print('Date and Time = ', dt2) dt3 = datetime(2016, 12, 31, 22, 33, 44, 123456) print('Date and Time = ', dt3)
Python timestamp function
The Python timestamp function returns the POSIX timestamp of the given datetime. Here, we are returning the timestamp of the current date and time.
from datetime import datetime dt = datetime.now() print('Today\'s Date = ', dt) print('Timestamp = ', dt.timestamp())
Python utcfromtimestamp
The Python utcfromtimestamp method returns the UTC datetime from the given timestamp.
from datetime import datetime tm_stamp = datetime.utcfromtimestamp(123456789) print('Date = ', tm_stamp) tm_stamp2 = datetime.utcfromtimestamp(482056789) print('Date = ', tm_stamp2) tm_stamp3 = datetime.utcfromtimestamp(19023456789) print('Date = ', tm_stamp3) tm_stamp4 = datetime.utcfromtimestamp(12761456789) print('Date = ', tm_stamp4)
Python datetime replace
The Python replace function replaces the date and time parts with new values. The syntax of this Python datetime replace is
datetime.repalce(year = self.year, month = self.month, day = self.day, hour = self.hour, minute = self.minute, second = self.second, microsecond = self.microsecond, tzinfo = self.tzinfo)
We replaced hours, minutes, seconds, and microseconds from the current date and time.
from datetime import datetime dt = datetime.now() print('Date and Time = ', dt) date_replace = dt.replace(hour = 2) print('Date and Time = ', date_replace) date_replace2 = dt.replace(minute = 59) print('Date and Time = ', date_replace2) date_replace3 = dt.replace(second = 4) print('Date and Time = ', date_replace3) date_replace4 = dt.replace(microsecond = 7) print('Date and Time = ', date_replace4)
The following are the list of all the other attributes and functions available in Python datetime class.
from datetime import datetime dt = datetime.now() print('Date and Time = ', dt) print('Replace in Date = ', dt.replace(hour = 2)) print('Tzinfo from Date = ', dt.tzinfo) print('Tzname from Date = ', dt.tzname()) print('Timetz from Date = ', dt.timetz()) print('Timestamp from Date = ', dt.timestamp()) print('Time from Date = ', dt.ctime()) print('isoweekday from Date = ', dt.isoweekday()) print('astimezone from Date = ', dt.astimezone()) print('utcoffset from Date = ', dt.utcoffset()) print('Daylight Saving from Date = ', dt.dst())
Python datetime combine
The Python combine function returns a new datetime object by combining the given date value and time. The syntax of this Python combine is
datetime.combine(date, time, tzinfo = self.tzinfo)
First, we declared a custom date and a custom time. Next, we used the Python combine function to combine those objects and return the date and time. From that date and time, we are returning date and time parts using the available attributes.
import datetime dt = datetime.date(2018, 12, 31) tm = datetime.time(23, 59, 58) combine_dt = datetime.datetime.combine(dt, tm) print('Date = ', dt) print('Time = ', tm) print('Date and Time = ', combine_dt) print('Year = ', combine_dt.year) print('Month = ', combine_dt.month) print('Day = ', combine_dt.day) print('Hour = ', combine_dt.hour) print('Minute = ', combine_dt.minute) print('Second = ', combine_dt.second) print('Microsecond = ', combine_dt.microsecond)
This example uses the combine function that combines the date and time. However, this time we are not providing the second’s value.
import datetime dt = datetime.date(2018, 12, 31) tm = datetime.time(23, 0) combine_dt = datetime.datetime.combine(dt, tm) print('Date = ', dt) print('Time = ', tm) print('Date and Time = ', combine_dt)
Python datetime Date class
The Python datetime module has the date class used to manipulate or work with dates. We use the Python today method to return the current date.
from datetime import date dt = date.today() print('Today\'s Date = ', dt)
The Python date class in the datetime module has three important attributes.
- date.min: It returns the earliest or minimum representable date.
- date.max: It returns the latest or maximum representable date.
- date.resolution: It returns the smallest possible difference between continuous dates.
from datetime import date print('Minimum Date = ', date.min) print('Maximum Date = ', date.max) print('Resolution = ', date.resolution)
Python date class attributes
This example shows the list of date attributes available in python. Here, year attribute returns the year from the current date, month = month number, day = day of the month, and weekday = weekday
from datetime import date dt = date.today() print('Today\'s Date = ', dt) print('Year from Current Date = ', dt.year) print('Month from Current Date = ', dt.month) print('Day from Current Date = ', dt.day) print('Weekday Number = ', dt.weekday())
Create date using Python date
The date class in the datetime module has the date function to create a custom date from the year, month, and day of the month.
from datetime import date dt = date(2018, 1, 31) print('Date = ', dt)
The Python fromtimestamp function accepts the POSIX timestamp value as an argument and returns the date from it.
from datetime import date tm_stamp = date.fromtimestamp(123456789) print('Date = ', tm_stamp) tm_stamp2 = date.fromtimestamp(412056789) print('Date = ', tm_stamp2) tm_stamp3 = date.fromtimestamp(9123456789) print('Date = ', tm_stamp3) tm_stamp4 = date.fromtimestamp(8761456789) print('Date = ', tm_stamp4)
datetime Time class
The Python datetime module has the time class, which helps us to work with the time and manipulate them. This example uses the Python time method to return 00:00:00.
from datetime import time tt = time() print('Time = ', tt)
The Python time class in the datetime module has the following 3 important attributes.
- time.min: It returns the earliest or minimum representable time.
- time.max: Returns the latest or maximum representable time.
- time.resolution: Smallest possible difference between time.
from datetime import time print('Minimum Time = ', time.min) print('Maximum Time = ', time.max) print('Resolution = ', time.resolution)
Create Time using Python time
Here, we are using the time function to construct or create a time with 10 hours, 22 minutes, and 33 seconds
from datetime import time tt = time(10, 22, 33) print('Time = ', tt)
This Python time example is an extension of the above. Here, we are using the microseconds and the argument names as well.
from datetime import datetime, time tme = datetime.time(datetime.now()) print('Current Time = ', tme) tt = time() print('Time = ', tt) tt1 = time(10, 22, 45) print('Time = ', tt1) tt2 = time(11, 34, 49, 890765) print('Time = ', tt2) tt3 = time(hour = 17, minute = 11, second = 33) print('Time = ', tt3) tt4 = time(hour = 17, minute = 22, second = 55, microsecond = 223344) print('Time = ', tt4)
Python time attributes
This example shows the list of available time attributes in python. Here, hour attribute returns the Hour from a given time, minute, second, and microsecond
from datetime import time tt = time(10, 50, 33) print('Time = ', tt) print('Hours = ', tt.hour) print('Minutes = ', tt.minute) print('Seconds = ', tt.second) print('Microseconds = ', tt.microsecond)
Python timedelta
The timedelta function in the datetime module is useful to predict or return the past and future dates. In this example, we are returning the date and time after one year and two years before. I suggest you to refer to Python timedelta.
from datetime import datetime, timedelta dt = datetime.now() print('Date and Time = ', dt) future_dt = dt + timedelta(days = 365) print('Future Date and Time = ', future_dt) past_dt = dt - timedelta(days = 730) print('Past Date and Time = ', past_dt)
Python strftime
The strftime function in datetime module formats the date in the specified format, and return the date as a string. Here, %Y-%m-%d’ means Year-Month-Day (2019-01-31). I suggest you refer to Python strftime.
from datetime import datetime dt = datetime.now() print('Date and Time = ', dt) dt2 = dt.strftime('%Y-%m-%d') print('Date and Time = ', dt2) dt3 = dt.strftime('%Y/%m/%d %H:%M:%S %p') print('Date and Time = ', dt3) dt4 = dt.strftime('%B %d, %Y %I-%M-%S %p') print('Date and Time = ', dt4)
Python strptime
The strptime is helpful to convert the string representation of the date to a regular date and time. Here, datetime.strptime(dt_str, ‘%d %B %Y’) means string date is passes in Day Month_Name Year format. Please refer to the Python strptime.
from datetime import datetime dt_str = '31 December 2017' dt_value = datetime.strptime(dt_str, '%d %B %Y') print('Date and Time = ', dt_value) dt_str2 = '15/8/17 22:33:55' dt_value2 = datetime.strptime(dt_str2, '%d/%m/%y %H:%M:%S') print('Date and Time = ', dt_value2)