Friday, 15 July 2016

Python: time module

time module provides number of time related functions. All the functions provided by time module are not available on all platforms.

Following are some of the conventions you should aware while using time module.

Epoch : It is point where time starts. On UNIX systems epoch is 1970. 'time.gmtime(0)' returns the epoch value in python.

>>> import time
>>> time.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)
>>> 

All the dates and times represented internally as seconds since epoch. Time can be represented as floating point value (or) as a time tuple (Using struct_time class).

struct_time class
strut_time class is used to represent the time in convenient way. It is the return type for the methods gmtime(), localtime(), and strptime().

>>> import time
>>> time.gmtime()
time.struct_time(tm_year=2015, tm_mon=11, tm_mday=9, tm_hour=14, tm_min=18, tm_sec=48, tm_wday=0, tm_yday=313, tm_isdst=0)

As you observe above code snippet, gmtime() method returns struct_time object. Following table describes each value of the struts_time instance.

Index
Attribute
Description
0
tm_year
Specifies the year
1
tm_mon
Specifies the month between 1-12
2
tm_mday
Specifies the day between 1-31
3
tm_hour
Specifies the hour between 0-23
4
tm_min
Specifies the minute between 0-59
5
tm_sec
Specifies the seconds between 0-59
6
tm_wday
Specifies the day between 0-6(MON-SUN)
7
tm_yday
Specifies the day between 1-366
8
tm_isdst
Represent day light saving, has 3 values -1, 0, 1.
You can access the values of struct_time using index notation.

>>> import time
>>> current_time=time.gmtime()
>>> 
>>> print("year:",current_time[0])
year: 2015
>>> print("month:",current_time[1])
month: 11
>>> print("today date:",current_time[2])
today date: 9





Previous                                                 Next                                                 Home

No comments:

Post a Comment