Python Date & Time
Date & Time
Dates and timings are very important for computers. Computers keeps tracks of date and time for files, documents and various other operations.
Similarly python uses date and time to perform several operations.
Example:
Output:
So, what can we understand from the about output? What does a bunch of random numbers mean?
These numbers are nothing but the number of ticks since the start of January 1, 1970 also called as epoch.
Now, one might ask what are ticks?
Ticks are floating point numbers measured in units of seconds for time interval.
We can also pass the epoch inside the ctime() function (or simply use the ctime() function) to print the current time in human readable format.
Example:
Output:
time.sleep():
the sleep() function inside time module is used to delay execution of current time thread by the given number of seconds.
Example:
Output:
As we can see, the sleep() will delay the execution 10 seconds.
Time.struct_time_Class:
Index | Field | Attribute | Value | Meaning | Format Codes |
0 | Year | tm_year | 0000, ………., 9999 | Four digit year | %Y |
1 | Month | tm_mon | 1 – January, 2 – February, ……., 12 - December | Months in a year | %m |
2 | Day | tm_mday | 1, 2, 3, ……., 29, 31 | Days in a month | %d |
3 | Hour | tm_hour | 0, 1, 2, ……., 22, 23 | Hours in a day | %H |
4 | Minute | tm_min | 0, 1, 2, ……., 58, 59 | Minutes in an hour | %M |
5 | Second | tm_sec | 0, 1, 2, ……., 60, 61 | Seconds in a minute | %S |
6 | Day of Week | tm_wday | 0 – Monday, 1 – Tuesday, ……., 6 – Sunday | Days in a week | %w |
7 | Day of Year | tm_yday | 1, 2, 3, ……., 355, 356 | Days in a year | %j |
8 | Daylight savings | tm_isdst | -1, 0, 1 |
|
|
time.localtime():
To get the output of local time in struct_time format, use the localtime() function.
Example:
Output:
time.gmtime():
To get the output of Coordinated Universal Time in struct_time format, use the gmtime() function.
Example:
Output:
time.mktime():
We also have the reverse of localtime() function that prints seconds passed since epoch in local time.
Example:
Output:
time.asctime():
The asctime() function takes struct_time and prints a single string representing it.
Example:
Output:
time.strptime():
This function parses string based on given format and returns it in struct_time format.
Example:
Output:
Calendar:
We can even print a calendar for a particular month. This can be done using the calendar module.
Example:
Output: