Repository navigation
Date & Time
Farrokh Karimi edited this page Jan 27, 2019
·
2 revisions
A Python program can handle date and time in several ways. Converting between date formats is a common chore for computers. Python's time and calendar modules help track dates and times.
Time intervals are floating-point numbers in units of seconds. Particular instants in time are expressed in seconds since 12:00am, January 1, 1970(epoch).
There is a popular time module available in Python which provides functions for working with times, and for converting between representations.
Example:
#!/usr/bin/python3
import time; # This is required to include time module.
ticks = time.time()
print ("Number of ticks since 12:00am, January 1, 1970:", ticks)Result:
Number of ticks since 12:00am, January 1, 1970: 1455508609.34375
Example:
import time
print (time.localtime())Result:
time.struct_time(tm_year = 2016, tm_mon = 2, tm_mday = 15, tm_hour = 9,
tm_min = 29, tm_sec = 2, tm_wday = 0, tm_yday = 46, tm_isdst = 0)
Example:
#!/usr/bin/python3
import time
print ("ctime : ", time.ctime())Result:
ctime : Mon Feb 15 09:55:34 2016
Example:
#!/usr/bin/python3
import time
print ("Start : %s" % time.ctime())
time.sleep( 5 )
print ("End : %s" % time.ctime())Result:
Start : Mon Feb 15 12:08:42 2016
End : Mon Feb 15 12:08:47 2016
The calendar module gives a wide range of methods to play with yearly and monthly calendars.
Example:
#!/usr/bin/python3
import calendar
cal = calendar.month(2016, 2)
print ("Here is the calendar:")
print (cal)Result:
Here is the calendar:
February 2016
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