Using time module

The time module provides the current date and time using time() function
The time.time() returns the number of second elapsed from 1/1/1970 12:00 am till current date and time called as ticks

>>> import time
>>> time.time()
1522211915.914467

We can also convert these ticks into actual date and time using function time.localtime()

>>> time.localtime(time.time())
time.struct_time(tm_year=2018, tm_mon=3, tm_mday=28, tm_hour=10, tm_min=10, tm_sec=0, tm_wday=2, tm_yday=87, tm_isdst=0)

It returns a structure having different fields for date and time which we can convert into date or time format

>>> t=time.localtime(time.time())
>>> currentdate='%02d-%02d-%d' % (t.tm_mday,t.tm_mon,t.tm_year)
>>> currentdate
'28-03-2018'

>>> currenttime='%02d-%02d-%02d' % (t.tm_hour,t.tm_min,t.tm_sec)
>>> currenttime
'10-12-05'


We can also use this structure inside the functions and classses

For Example
Create a class MyTime having a function now() which returns the current time with am and pm

import time
class MyTime:
    def now():
        t=time.localtime(time.time())
        tm='%02d-%02d-%d' % (t.tm_hour,t.tm_min,t.tm_sec)
        if t.tm_hour<12:
            tm=tm+" am"
        else:
            tm=tm+" pm"
        return tm

print(MyTime.now())


Comments

Popular posts from this blog

Converting Excel File to JSON File using xlrd module

Using Oracle with Python