Python Date and Time – Syntax and examples
1. Python Date and Python Time
Our last session was on data types and constructs of Python. Here, we will talk about Python date and time module. Moreover, we will discuss what is Python Time and Python Date. Along with this, we will learn about Python time tuple and Python time module.
A computer often has to perform the task of converting between different date and time formats. For this, Python provides time and calendar modules.
So, let’s start Python Date and Time.
2. Introduction to Python Date and Time
To see how Python handles date and time, let’s first look at some important concepts of Python time. you can refer to our article on Python Datetime Module with Quick Examples
The Epoch is the point in time in Python from which time is measured. It is labelled 12:00AM, Jan 1, 1970. It is the beginning of an era.
In Python, a tick is a floating-point number in seconds, and it denotes a time interval in Python. Ticks are calculated from the epoch.
c. Daylight Savings Time(DST)
In Agrarian culture, they set the clocks to be one hour faster. This way, they get up an hour before actual sunrise and get an hour extra after work. In northern and southern regions, days are considerably longer in the summer. However, in areas around the equator, the difference isn’t that much for DST to be efficient. Hence, not every country implements it. Before proceeding on Python time tuple you may also want to read our article on python tuples.
3. Python Time Tuple
We represent Python time in a way that’s easy for us to understand. However, Python stores it in tuples. These python tuples are made of nine numbers.
|Index||Field||Domain of Values|
|0||Year (4 digits)||Ex.- 1995|
|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/61 are leap seconds)|
|6||Day of Week||0 to 6 (Monday to Sunday)|
|7||Day of Year||1 to 366 (Julian day)|
Leap seconds are added to make up to Earth’s slowing rotation. When DST is 0, it isn’t applied. When it’s 1, it is applied. However, when it is -1, it is up to the library to determine that.
This tuple has an equivalent struct_time structure.
4. Getting the Number of Ticks
First, we’ll look at the Python ‘time’ module. To use functions from it, you must import it in your program. See h
>>> import time
If you wanted to import a single method from ‘time’, you would do it this way.
>>> from time import time >>> time()
To get how many ticks have passed since the epoch, we call the Python time() method.
>>> import time >> time.time()
This is the number of ticks that have yet passed from the epoch. Clearly, this isn’t very human-readable. We can read it, but with only this information, we can’t instantly perceive how much time has passed. Read our article on Python Functions with Syntax and Examples
5. Getting the Local Time
To get the current time in Python in a more perceivable Python Date Time format, we use the localtime() method instead. It returns the Python time according to the area you’re in.
time.struct_time(tm_year=2017, tm_mon=12, tm_mday=28, tm_hour=20, tm_min=17, tm_sec=48, tm_wday=3, tm_yday=362, tm_isdst=0)
This still isn’t completely instantly perceivable. Let’s try something else yet.
6. Getting the Formatted Time
When we use the asctime() method, we get something much more readable.
‘Thu Dec 28 20:22:55 2017’
It only takes us about a second to read this and understand.
You can also provide a tuple or a struct_time structure as an argument.
‘Thu Dec 28 20:24:52 2017’
But the plain time() method doesn’t work with it.
Traceback (most recent call last):
File “<pyshell#31>”, line 1, in <module>
TypeError: Tuple or struct_time argument required
7. Python Calendar
‘calendar’ is yet another module available in Python. It lets you play with monthly and yearly calendars using a variety of functions.
To get the calendar for Dec 2017, we use the month() method.
‘ December 2017\nMo Tu We Th Fr Sa Su\n 1 2 3\n 4 5 6 7 8 9 10\n11 12 13 14 15 16 17\n18 19 20 21 22 23 24\n25 26 27 28 29 30 31\n’
I’m guessing we should use the print function here to make this readable.
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
8. Methods in the Python Time Module
Do refer Python Method – Classes, Objects and Functions in Python before proceeding.
The three methods we discussed aren’t the only ones applicable on the Python time module. One by one, we’ll see them all.
We already saw this in section 4. Let’s get the number of ticks once again.
This method does not take any parameters. And if you set the clock back before making another call to this method, it may return a lower value.
This is the second method we discussed in the text. It returns the current time according to your geographical location, in a more readable format.
time.struct_time(tm_year=2017, tm_mon=12, tm_mday=28, tm_hour=21, tm_min=2, tm_sec=13, tm_wday=3, tm_yday=362, tm_isdst=0)
This returns a time tuple.
However, localtime() may take an argument in seconds. Then, it returns a time tuple for that number of seconds from the epoch. First, let’s try providing 0 seconds as an argument.
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=5, tm_min=30, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
We just discussed that epoch is 12:00, Jan 1, 1970. Why then did it return 5:30? Well that’s because we’re here in India. Our time zone is UTC+05:30 (UTC stands for Coordinated Universal Time).
Now, let’s try it for 777 seconds.
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=5, tm_min=42, tm_sec=57, tm_wday=3, tm_yday=1, tm_isdst=0)
This method gives us the current time in a very readable format. It returns a string of 24 characters.
‘Thu Dec 28 21:17:39 2017’
It may also take a Python time tuple as an argument. Since the localtime() method returns a time tuple, let’s use it as the argument.
‘Thu Dec 28 21:21:36 2017’
The clock method does not take any arguments. On Windows, it returns the number of seconds elapsed since the first call made to it. It returns the value as a floating number. Let’s try it a few times.
However, it does not return 0.0 on every first call.
Now, if you restart the shell, the next time you call it, it will assume it to be the first call.
Remember the problem we faced in localtime(0), about UTC? Well, gmtime() converts the current time into UTC before returning it.
time.struct_time(tm_year=2017, tm_mon=12, tm_mday=28, tm_hour=16, tm_min=11, tm_sec=3, tm_wday=3, tm_yday=362, tm_isdst=0)
It may also take seconds as an argument. Let’s try gmtime(0).
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
Like localtime(), it returns a time tuple.
This method is equivalent to asctime().
The mktime() method takes a time tuple as an argument, and returns the equivalent amount of ticks/seconds. It returns in floating point.
You can’t however call it without an argument.
Traceback (most recent call last):
File “<pyshell#72>”, line 1, in <module>
TypeError: mktime() takes exactly one argument (0 given)
When called, sleep() holds the execution for a given amount of seconds. This number is passed to it as an argument.
>>> time.asctime(); time.sleep(2); time.asctime()
‘Thu Dec 28 22:11:55 2017’
‘Thu Dec 28 22:11:57 2017’
Now what if you wanted to display the Python date and time in the format you wish to? The strftime() method takes a format and optionally, a Python time tuple, and returns the date in the format you specify. The syntax is as follows.
You can apply the following directives in the format, as per your need.
- %a – abbreviated day of week
- %A – full day of week
- %b – abbreviated name of month
- %B – full name of month
- %c – preferred date and time representation
- %C – century number (the year divided by 100; range 00 to 99)
- %d – day of month (1 to 31)
- %D – the same as %m/%d/%y
- %e – day of month (1 to 31)
- %g – like %G, but without the century
- %G – 4-digit year corresponding to the ISO week number (ref. %V).
- %h – same as %b
- %H – hour; using a 24-hr clock (0 to 23)
- %I – hour; using a 12-hr clock (1 to 12)
- %j – day of year (1 to 366)
- %m – month (1 to 12)
- %M – minute
- %n – newline character
- %p – AM/PM according to given time value
- %r – time in AM/PM representation
- %R – time in 24-hr representation
- %S – second
- %t – tab
- %T – current time; equal to %H:%M:%S
- %u – day of week as a number (1 to 7); Monday=1
- %U – week of year, beginning with the first Sunday as the first day of the first week
- %V – The ISO 8601 week of year (1 to 53); week 1 is the first with at least 4 days in the current year, and with Monday as the first day of the week
- %W – week of year; beginning with the first Monday as the first day of the first week
- %w – day of week as a decimal; Sunday=0
- %x – the preferred date representation without the time
- %X – the preferred time representation without the date
- %y – year without century (00 to 99)
- %Y – year including century
- %Z or %z – time zone/name/abbreviation
- %% – a % character
Let’s try printing the shortened name of the month in the local time in Python.
Let’s try another one.
>>> time.strftime("%B %uth, '%y",time.localtime())
“December 4th, ’17”
As you can see, it is possible to add letters in this python string normally.
j. Python strptime()
We just saw that the strftime() method returns a string from a format (and optionally, a tuple). The strptime() takes such a string and parses it. Finally, it returns a time tuple. It takes two arguments; the following is the syntax.
>>> time.strptime("31 Dec 1995","%d %b %Y")
time.struct_time(tm_year=1995, tm_mon=12, tm_mday=31, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=365, tm_isdst=-1)
9. Attributes of the time Module
This returns the local DST timezone’s offset. While it returns a positive value for locations west of UTC, it returns a negative value for those east of UTC.
From where we write this article, we can tell that we live east of UTC. Note that this attribute’s value does not change for a location.
The timezone attribute is the same as altzone, but it does not consider the DST.
Finally, you can use this attribute to print the name of the local time zone with and without DST.
(‘India Standard Time’, ‘India Daylight Time’)
10. Methods in the calendar Module
Like the time module, calendar provides us with some methods too. Let’s see what we can do with it.
isleap() takes a 4-digit year as an argument, and returns True if it is a leap year. Otherwise, it returns False.
Talking of leap years, this one returns the total number of leap days from year y1 to year y2.
This one returns which day is currently set as the first day of the week. By default, this is 0.
Complementary to what we learnt in the above point, setfirstweekday() allows us to set the first day of the week to what we want. 0 is for Monday, 6 is for Sunday.
>>> calendar.setfirstweekday(4) >>> calendar.firstweekday()
Now, let’s print the calendar for this January.
Fr Sa Su Mo Tu We Th
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
As you can see, the calendar now begins at Friday. However, this change of information is invalidated once the shell is restarted. That is, it changes back to 0.
As we have seen so far in this document, month() returns a calendar for a certain month of a certain year. These are two of the arguments. There are two other optional arguments- one for width of characters in name of day, and one for the number of lines for each week.
Mon Tue Wed Thu Fri Sat Sun
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
The calendar() method returns the calendar for an entire year. It may also take three optional parameters. These are- width of characters for day of week, lines for week, spaces between columns.
This method returns a list of lists of day numbers as lists. Also, it takes two arguments- year and month.
>>> print(calendar.monthcalendar(2017,12))[[0, 0, 0, 0, 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]]
Now this method takes two arguments- year and month. Then, it returns the day of week for the first day of the month, and the number of days in the month.
Here, 4 is for Friday.
If you want to skip the print statement to the calendar method, use prcal() instead. Let’s take the following code.
Its output is the same as of the code in point 6 in this section.
It’s the same thing here as well. It prints out the calendar for the specified month.
This method takes as arguments the year, the month, and the day. Then, it returns which day of the week it is.
Finally, this method takes a time tuple and returns the equivalent in ticks since the epoch, in floating point.
So, this was all about Python Date and Time. Hope you like our explanation.
We learned a lot today, didn’t we? First, we learned about some concepts of Python date and time like the epoch, ticks, and DST. Then, we used the Python time and calendar modules, and their methods and attributes. Why don’t you try and use this knowledge to create a console-based game?
Still, Confuse in Python Date and Time? Share your query/ feedback with us in the comments section