Date and Time handling in Python

vegaseat 2 Tallied Votes 2K Views Share

We take a look at the various functions of module time, counting seconds and milliseconds, measuring the time a simple for-loop takes, inspect a list of time data and ways to display it in a useful manner. An attempt is made to find the day of the week, given a date a few years old. Like, what day of the week was your friend born. Hope he or she isn't too old, there is a limit to everything in life!

# handling date/time data
# Python23 tested   vegaseat   3/6/2005

import time

print "List the functions within module time:"
for funk in dir(time):
  print funk

print time.time(), "seconds since 1/1/1970 00:00:00"
print time.time()/(60*60*24), "days since 1/1/1970"

# time.clock() gives wallclock seconds, accuracy better than 1 ms
# time.clock() is for windows, time.time() is more portable
print "Using time.clock() = ", time.clock(), "seconds since first call to clock()"
print "\nTiming a 1 million loop 'for loop' ..."
start = time.clock()
for x in range(1000000):
  y = x  # do something
end = time.clock()
print "Time elapsed = ", end - start, "seconds"

# create a tuple of local time data
timeHere = time.localtime()
print "\nA tuple of local date/time data using time.localtime():"
print "(year,month,day,hour,min,sec,weekday(Monday=0),yearday,dls-flag)"
print timeHere

# extract a more readable date/time from the tuple
# eg.  Sat Mar 05 22:51:55 2005
print "\nUsing time.asctime(time.localtime()):", time.asctime(time.localtime())
# the same results
print "\nUsing time.ctime(time.time()):", time.ctime(time.time())
print "\nOr using time.ctime():", time.ctime()

print "\nUsing strftime():"
print "Day and Date:", time.strftime("%a %m/%d/%y", time.localtime())
print "Day, Date   :", time.strftime("%A, %B %d, %Y", time.localtime())
print "Time (12hr) :", time.strftime("%I:%M:%S %p", time.localtime())
print "Time (24hr) :", time.strftime("%H:%M:%S", time.localtime())
print "DayMonthYear:",time.strftime("%d%b%Y", time.localtime())

print

print "Start a line with this date-time stamp and it will sort:",\
    time.strftime("%Y/%m/%d %H:%M:%S", time.localtime())

print

def getDayOfWeek(dateString):
  # day of week (Monday = 0) of a given month/day/year
  t1 = time.strptime(dateString,"%m/%d/%Y")
  # year in time_struct t1 can not go below 1970 (start of epoch)!
  t2 = time.mktime(t1)
  return(time.localtime(t2)[6])

Weekday = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
  'Friday', 'Saturday', 'Sunday']

# sorry about the limitations, stay above 01/01/1970
# more exactly 01/01/1970 at 0 UT (midnight Greenwich, England)
print "11/12/1970 was a", Weekday[getDayOfWeek("11/12/1970")]

print

print "Calculate difference between two times (12 hour format) of a day:"
time1 = raw_input("Enter first time (format 11:25:00AM or 03:15:30PM): ")
# pick some plausible date
timeString1 = "03/06/05 " + time1
# create a time tuple from this time string format eg. 03/06/05 11:22:00AM
timeTuple1 = time.strptime(timeString1, "%m/%d/%y %I:%M:%S%p")

#print timeTuple1   # test eg. (2005, 3, 6, 11, 22, 0, 5, 91, -1)

time2 = raw_input("Enter second time (format 11:25:00AM or 03:15:30PM): ")
# use same date to stay in same day
timeString2 = "03/06/05 " + time2
timeTuple2 = time.strptime(timeString2, "%m/%d/%y %I:%M:%S%p")

# mktime() gives seconds since epoch 1/1/1970 00:00:00
time_difference = time.mktime(timeTuple2) - time.mktime(timeTuple1)
#print type(time_difference)  # test <type 'float'>
print "Time difference = %d seconds" % int(time_difference)
print "Time difference = %0.1f minutes" % (time_difference/60.0)
print "Time difference = %0.2f hours" % (time_difference/(60.0*60))

print

print "Wait one and a half seconds!"
time.sleep(1.5)
print "The end!"

Dani AI

Generated

A useful, compact primer by that demonstrates the old-school time API and strftime/strptime tricks; ’s comment shows it helped others. The script is Python 2 era: time.clock() behaved inconsistently across platforms, was deprecated and removed (use the newer, clearer timers instead). For measuring elapsed time prefer time.perf_counter() (high-resolution, includes sleep), use time.process_time() for CPU-only measurements, and time.monotonic() for timers that must not be affected by system-clock changes. See the Python 3.8 removal note and the time module documentation.
What’s New in Python 3.8 (time.clock removed). time module docs. (docs.python.org)

For date math and birthdate lookups, prefer the datetime API with timezone-aware datetimes instead of relying on epoch-conversions like mktime() (which can be platform-limited — e.g. 1970–2038 on some systems). Use datetime.now(timezone.utc) (rather than naive utcnow()), and use zoneinfo (added in Python 3.9) or a well-maintained library when you need IANA zone data. Use the fold attribute (PEP 495) to disambiguate repeated local times at DST fall-back. See the datetime docs, zoneinfo, and PEP 495 for details.
datetime docs. zoneinfo. PEP 495. Deprecations (utcnow). (docs.python.org)

For ’s custom clock, model it as a deterministic mapping: pick a fixed epoch (store it as an ISO-8601, timezone-aware datetime), measure real elapsed seconds with perf_counter() or monotonic() to avoid system-clock jumps, then convert elapsed seconds into the fictional units with integer arithmetic (use nanoseconds or perf_counter_ns() to avoid float drift). Implement the two modes as a scale factor (regular vs fast). Persist epoch + mode so the clock is reproducible. Minimal skeleton approach (conceptual only):

from time import perf_counter
from datetime import datetime, timezone

EPOCH = datetime(9977,1,1, tzinfo=timezone.utc)
t0 = perf_counter()
# later:
elapsed_s = perf_counter() - t0
planet_seconds = int(elapsed_s * SCALE)   # SCALE encodes your unit mapping

Using datetime + monotonic/perf counters keeps the implementation robust and reproducible. See the time and datetime docs for precise behavior and caveats. (docs.python.org)

vamsicoolman 0 Newbie Poster

Thanks for the post helped me a lot...

Kanem 0 Newbie Poster

i am trying to build a clock using python where the clock is about 1/2 an earth second, it would have 11 seconds in a minute, it would have 5 minutes in an hour, and it would have 3 hours in a day. it would also have 3 months per year, each month would be 5, 3 and 4 days respectively. And its current year now is 9977. it would have 2 modes, a fast mode and a regular mode.
I need to know how to start this, how to defined the variables and functions.
Can anyone please help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.