Python datetime Module
FREE Online Courses: Elevate Your Skills, Zero Cost Attached - Enroll Now!
There are many ways to handle date and time in python. It is common to convert between dated formats for any computer. Python contains date and calendar modules to help track dates and times.
To work with date and time in python, we have a module known as datetime. This module is built in python and does not require external downloads. The module offers classes and methods to work with date and time. Date and datetime are different objects in python and manipulating them does not manipulate the objects but not the strings or timestamps.
The date time module is briefly divided into six classes:
1. Date:
A naive date that comprises the year, month, and day as per the current Gregorian calendar.
2. Time:
The time is independent of any particular day and assumes the day has 24*60*60 seconds. It has attributes such as hour,minute, second,microsecond and tzinfo
3. Datetime:
It combines date and time and has attributes such as month, day, year, hour,minutes, seconds, microseconds and tzinfo.
4. Timedelta:
A time duration that expresses the difference between two date, two time or two datetime instances up till microsecond resolution.
5. Tzinfo:
It provides objects on time zone information
6. Timezone:
Implements tzinfo abstract base class as a fixed offset from the UTC.
Date class in Python
The date class creates date objects in python. The format of the object is in the form YYYY-MM-DD. The constructor takes in three arguments, year ,month and day.
Syntax for the constructor:
Class datetime.date( year,month, day)
The range for the arguments must be:
MINYEAR<= year<= MAXYEAR
1<= month <= 12
1<= day<+ number of days in the given month or year.
Example1:
Date object representing date in python
From datetime import date mydate= date(2022, 05, 08) print(“date passed as an argument is”, mydate)
Output:
Example 2:
Get current date
today() function of date class returns the local date. It contains attributes such as ( year, month and day) we can print these separately
From datetime import date today= date.today() print(today)
Output:
Example 3:
Get today’s month, year and day
The date class attributes of day, month and year can be used to get the day,month and year from the date object.
From datetime import date today= date.today() print(today.year) print(today.month) print(today.day)
Output:
05
08
Example 4:
Get date from timestamp
We create date objects from timestamps with the help of the fromtimestamp() method. The timestamp is the number of seconds that passed from 1st January 1970 at UTC to any given date.
from datetime import datetime date_time = datetime.fromtimestamp(1887639468) print("Datetime from timestamp:", date_time)
Output:
Example 5:
Convert date to string
isoffromat(0 and tostring() are two functions to use when you want to convert any date object to a string representation.
From datetime import date today= date.today() str= date.isoformat(today) print(“string representation”, str) print(type(str))
Output:
String Representation 2022-05-08<class ‘str’>
Python Date class methods
Class name | Description |
ctime() | Returns string with date representation |
fromisocalendar() | Returns date in the iso calendar |
fromisoformat() | Returns date object from the string representation of date |
fromordinal() | Returns date from the proleptic Gregorian ordinal where January 1 of year 1 is ordinal 1 |
fromtimestamp() | Returns date object from POSIX timestamp |
isocalendar() | Returns tuple year, week and weekday |
isofromat() | Returns string representation of date |
isoweekday() | Gives the day of the week as a number and monday is 1 and sunday is 7 |
replace() | Transforms the value of the date object with the given format |
strfime() | Return string representation of the date with the given format |
timetuple() | Returns object of type time.struct_time |
today() | Gives local current date |
toordinal() | Gives the proleptic Gregorian ordinal of the date where January 1 of year 1 is ordinal 1 |
weekday() | Returns the day of the week as integer where monday is 0 and sunday is 6 |
Python Time class
The time class creates time object which represents local time independent of any day
constructor syntax :
class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
The arguments given above are completely optional. Tzinfo can be null otherwise all the arguments must be integers in the following ranges:
0<= hour <=24
0<= minute< 60
0<= second< 60
0<= microsecond<1000000
Fold in [0,1]
Example 1:
Time object representing time in python
From datetime import time new_time= time(13, 24, 56) print(“ time entered is”, new_time) new_time=time(minute=12) new_time=time() print(“time without argument”, new_time)
Output:
time without argument 00:00:00
Example 2:
Get hours, minutes, seconds and microseconds
From datetime import time time= time(11, 34, 56) print(time.hour) print(time.minute) print(time.seconds) print(time.microsecond)
Output:
34
56
0
Example 3:
Convert time object to string
From datetime import time Time = time( 12, 24, 36, 1212) str= Time.isoformat() print(str) print(type(str))
Output:
<class ‘str’>
List of Python time class methods
Class Name | Description |
dst() | Returns tzinfo.dst() is tzinfo is not none |
fromisofromat() | Returns time object from the string representation of time |
isoformat() | Return string representation of time from time object |
replace() | Changes value of the time object with the given parameter |
strftime() | Return string representation of time with the given format |
tzname() | Returns tzinfo.tzname() is tzinfo is not none |
utcoffset() | Returns tzinfo.tzname() is tzinfo is not none |
Python Datetime class
The datetime class holds information for both date and time. Similar to the date object, datetime accuses the current Gregorian calendar and extends in both directions. Similar to the time object the datetime class assumes there are exactly 3600*24 seconds every day.
Constructor syntax:
class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
Example 1:
Datetime object representing datetime in python
From datetime import datetime a= datetime( 1999, 12 12) print(a) a= datetime(1999, 12, 12, 12 , 12 , 12, 342380) print(a)
Output
1999-12-12 12:12:12.342380
Example 2:
Get year, month, hour, minute and timestamp
After the creation of timestamp object print its attributes separately
From datetime import datetime a= datetime( 1999, 12, 12, 12, 12, 12) print(a.year) print(a.month) print(a.hour) print(a.minute) print(a.timestamp())
Output:
12
12
12
945000732
Example 3:
Get current date and time
datetime.now() function prints current date and time. now() functions gives the current local date and time.
From datetime import datetime today= datetime.now() print(today)
Output:
Example 4:
Convert python datetime to string
From datetime import datetime as dt now=dt.now() string=dt.isoformat(now) print(string) print(type(string))
Output:
<class ‘str’>
Python Timedelta class
The python timedelta class calculates the difference between two dates and can do other manipulation operations on dates.
Constructor syntax:
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) Returns : Date
Example 1:
Add days to datetime object
import datetime current_date = "12/6/20" current_date_temp = datetime.datetime.strptime(current_date, "%m/%d/%y") newdate = current_date_temp + datetime.timedelta(days=5) print(newdate)
Output:
Example 2:
Difference between two dates and two times
We can also calculate the Date and time difference
from datetime import datetime # dates in string format str_d1 = '2021/10/20' str_d2 = '2022/2/20' # convert string to date object d1 = datetime.strptime(str_d1, "%Y/%m/%d") d2 = datetime.strptime(str_d2, "%Y/%m/%d") # difference between dates in timedelta delta = d2 - d1 print(f'Difference is {delta.days} days')
Output:
Operations supported by time delta class include addition, subtraction, multiplication, division, floor division, modulo, timedelta, abds, str and repr(timedelta).
Format datetime in Python
The date representation differs from place to place and can be changed using format datetime. Strptime and strftime functions in python format date accordingly.
Python datetime strftime
strftime() function transforms the given date, time or datetime object to the string representation of the given format.
Example:
python datetime format
from datetime import datetime now = datetime.now() # current date and time year = now.strftime("%Y") print("year:", year) month = now.strftime("%m") print("month:", month) day = now.strftime("%d") print("day:", day) time = now.strftime("%H:%M:%S") print("time:", time) date_time = now.strftime("%m/%d/%Y, %H:%M:%S") print("date and time:",date_time)
Output:
month: 05
day: 08
time: 17:11:57
date and time: 05/08/2022, 17:11:57
Python datetime strptime
strptime() creates a datetime object from the given string
Example:
datetime strptime
from datetime import datetime date_string = "21 June, 2018" print("date_string =", date_string) print("type of date_string =", type(date_string)) date_object = datetime.strptime(date_string, "%d %B, %Y") print("date_object =", date_object) print("type of date_object =", type(date_object))
Output:
type of date_string = <class ‘str’>
date_object = 2018-06-21 00:00:00
type of date_object = <class ‘datetime.datetime’>
Handling python datetime timezone
We use timezones when we want to display the timezone of a specific region. We do this with the help of the pytz module of python. This module includes the date-time conversion methods and helps in serving international clients.
Example:
import datetime import pytz d = datetime.datetime.now() timezone = pytz.timezone("America/Los_Angeles") d_aware = timezone.localize(d) d_aware.tzinfo
Output:
What is tick in Python?
Time intervals are written in floating point numbers in the units of seconds. Any given instant of time is expressed in seconds since January 1, 1970 (epoch).
The popular module known as the time module is available in python which provides functions to operate with times and for converting between representations. When we call the function time.time(), it returns the current system time in ticks science January 1, 1970 (epoch) 00:00:00.
Consider the following example:
#!/usr/bin/python import time; # This is required to include in the time module. ticks = time.time() print "Number of ticks since 12:00am, January 1, 1970:", ticks
Output:
Date arithmetic is also easy to work with ticks. However, we cannot use this form to represent dates before epoch. Also dates in the far away feature also cannot be represented using this form. The cut off year is 2038 for Windows and UNIX.
What is time tuple in Python?
A lot of time, functions in python handle time with the help of 9 tuples as given below:
Index | Field | Values |
0 | 4-digit year | 2008 |
1 | month | 1 to 12 |
2 | day | 1 to 31 |
3 | Hour | 0 to 23 |
4 | minute | 0 to 59 |
5 | second | 0 to 61 (60 or 61 are leap seconds) |
6 | Day of week | 0 to 6, 0 being monday |
7 | Day of year | 1 to 366(Julian day) |
8 | Daylight savings | -1,0,1,-1 means library determines DST |
The above type is equal to struct_time structure. The structure has the following attributes:
Index | Attributes | Values |
0 | tm_year | 2008 |
1 | tm_mon | 1 to 12 |
2 | tm_mday | 1 to 31 |
3 | tm_hour | 0 to 23 |
4 | tm_min | 0 to 59 |
5 | tm_sec | 0 to 61(60 or 61 could be leap seconds) |
6 | tm_wday | 0 to 6, 0 is monday |
7 | tm_yday | 1 to 366 (Julian day) |
8 | tm_isdst | -1,0,1,-1 means library determine DST |
Getting current time in Python
Consider the following code in order to convert seconds since the epoch floating point value into a time tuple. In order to do so one must pass the floating point value to a function. This returns a tuple with 9 items valid.
Example:
#!/usr/bin/python import time; localtime = time.localtime(time.time()) print "Local current time :", localtime
Output:
Getting formatted time in Python
Users can format the time as per their choice. The formal method is to use the asctime()
#!/usr/bin/python import time; localtime = time.asctime( time.localtime(time.time()) ) print "Local current time :", localtime
Output:
Getting calendar for month
The calendar module offers you a wide range of modules to work with yearly and monthly calendars.
Let us print the calendar for a given month Jan 2021.
#!/usr/bin/python import calendar cal = calendar.month(2021, 1) print "Here is the calendar:" print cal
Output:
January 2021
Mo Tu We Th Fr Sa Su
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Python time module
The time module contains functions to work with times and for conversions between different representations.
Following is the list of methods available in the time module:
Sr. no | Function name | Function description |
1 | time.altzone | Returns the offset of the local DST timezone, in seconds west of UTC. it is negative if the local DST timezone is east of UTC. use only if the daylight is zero. |
2 | time.asctime([t]) | It takes in a time tuple and returns a readable form for the character string |
3 | time.clock() | Get the current processor time as the floating point number expressed in seconds |
4 | time.ctime([secs]) | Transforms the time in seconds since the epoch to a string that represents local time |
5 | time.gtime([secs]) | Converts time expressed in seconds since epoch to string that represent time in UTC |
6 | time.localtime([secs]) | Converts time expressed in seconds since epoch to local time |
7 | time.mktime(tupletime) | Converts a time-tuple in local time to time expressed in seconds since epoch |
8 | time.sleep(secs) | Postpones the calling thread for given seconds |
9 | time.strftime(fmt[,tupletime]) | Transforms the tuple or struct_time representing a time as returned by gmtime() or localtime() to string specified by the format argument |
10 | time.strptime(str, fmt=’%a%b%d%H:%M:%S%Y’) | Creates a datetime object from the given string . it takes in the string to convert and format code |
11 | time.time() | Return the current time which is a floating-point number in seconds since epoch |
12 | time.tzset() | Return all the rules of time conversion used by library routines. |
Python calendar module
S.No | Function name | Function description |
1 | calendar.calendar(year,w=2,l-1,c=6) | Returns a 3 column calendar for the whole year as a multi-line string |
2 | calendar.firstweekday() | Returns the current setting for weekday to start each week |
3 | calendar.isleap(year) | Return true if the input year is leap year and false otherwise |
4 | calendar.leapdays(y1,y2) | Return the number of leap years between any given range of years |
5 | calendar.month(year,month, w=2,l=1) | Gives the month calendar in a multi line string |
6 | calendar.monthcalendar(year, month) | Returns a matrix representing the calendar of the month |
7 | calendar.monthrange(year,month) | Gets the weekdays of the first day of months and number of days in month for any given year and month |
8 | calendar.prcal(year, w=2, l=1,c=6) | Prints the calendar for the complete year |
9 | calendar.prmonth(year, month, w=2, l=1) | Prints the calendar of the month |
10 | calendar.setfirstweekday(weekday) | Sets the weekday to start each week. 0 is monday and 6 is Sunday |
11 | calendar.timegm(tupletime) | Takes in the instant in time-tuple form and returns the same instant in floating-point number in seconds since epoch |
12 | calendar.weekday(year, month, day) | Gives the day of the week (0 is Monday) for giver year, month and day |
Conclusion
So this was it in the python date and time modules. We will look further in detail about the module in the next articles. We hope our explanation was easy to understand.
Hello, I just found your website and have to say I like the idea of projects and quizzes. However as someone who is self learning, I have to ask, where do I fin the information to be able to answer the theoretical questions if your quizzes?
Best regards
Yianni