Python DateTime Library

Last Updated On Tuesday 19th Apr 2022

DateTime Module in Python

Python offers just as much when it comes to time keeping. These functionalities reside in the datetime module.

DateTime in Python

The datetime classes are categorize into 6 main classes.

  • date – An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. Its attributes are year, month and day.
  • time – An idealized time, independent of any particular day, assuming that every day has exactly 24*60*60 seconds. Its attributes are hour, minute, second, microsecond, and tzinfo.
  • datetime – Its a combination of date and time along with the attributes year, month, day, hour, minute, second, microsecond, and tzinfo.
  • timedelta – A duration expressing the difference between two date, time, or datetime instances to microsecond resolution.
  • tzinfo – It provides time zone information objects.
  • timezone – A class that implements the tzinfo abstract base class as a fixed offset from the UTC.

DateTime

Syntax

	class datetime.date(year, month, day)
	

The arguments must be in the following range

  • MINYEAR <= year <= MAXYEAR
  • 1 <= month <= 12
  • 1 <= day <= number of days in the given month and year
	import datetime
from datetime import timedelta
time1 = datetime.datetime.now() # Create a datetime-object for right now
print("The time is:", time1) # Display current time unformatted

print("In other words it's a", time1.strftime("%A in %B"))
# Reduce time1.year-variable by ten

print("Ten years ago it was", time1.year-10)
# Use timedelta to move thirty days into the future
futuredate = datetime.timedelta(days=30)
futuredate += time1 # Add the current date to futuredate
print("Thirty days into the future it'll be", futuredate.strftime("%B"))
	
	The time is: 2021-09-11 08:22:36.067374
In other words it's a Saturday in September
Ten years ago it was 2011
Thirty days into the future it'll be October
	

Common Date Formatting in Python

	%A Full day of the week (e.g., Tuesday)
%B Full name of month (e.g., April)
%a Short day of the week (e.g., Tue)
%b Short name of month (e.g., Apr)
%Z Time zone (e.g., UTC)
%H Hour, 24h system (e.g., 21)
%p AM/PM
%I Hour, 12h system
	
	from datetime import datetime, timezone, timedelta

op1 = datetime.now()  # Current Local Time
print(op1)

tz = timezone(timedelta(hours=7))  # The Current Time in East Zone 7
op2 = datetime.now(tz)
print(op2)

op3 = datetime.utcnow()   # The Current UTC Time
print(op3)

op4 = op1 + timedelta(days=140, minutes=5)
print(op4) # datetime type + timedelta type

# Subtraction between  datetime, calculation interval (no addition)

data = op1 - op3
print(data.days, data.seconds / 60 / 60, data.microseconds)

# datetime type-datetime type
# datetime type comparison datetime type
	
	# 2021-09-11 09:08:46.169897
# 2021-09-11 16:08:46.169951+07:00
# 2021-09-11 09:08:46.169968
# 2022-01-29 09:13:46.169897
#-1 23.99972222222222 999929
	

Convert the TimeStamp to a DateTime object

	# Convert TIMESTAMP to datetime object without time zone
datetime.fromtimestamp(TIMESTAMP, tz=None)

# Convert TIMESTAMP to UTC datetime object without time zone
datetime.utcfromtimestamp(TIMESTAMP, tz=None)
	

The datetime object, output time according to the specified format

	from datetime import datetime

print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

# 2021-09-11 09:27:47

# You can specify the separator as a space, timespec: 3.6+

print(datetime.now().isoformat(sep='T',timespec='auto'))

# 2021-09-11T09:28:20.119706
	

Convert the time in a character format

	# 2011-11-11 00:00:00

from datetime import datetime

print(datetime.fromisoformat("2011-11-11"))

# Supported date and time format: YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[ :SS[.ffffff]]]]
	

Acts on a DateTime object and returns a string representing the date and time.

	from datetime import datetime

print(datetime.now().ctime())

# Sat Sep 11 09:25:25 2021