Time Handling in Python

In this article, I have shared how to manipulate time in Python.

A Python program can handle date & 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:00 AM, January 1, 1970(epoch).

The Epoch is the point in time in Python from which time is measured. It is labelled 12:00 AM, Jan 1, 2021. It is the beginning of an era.

In Agrarian culture, they set the clocks to be one hour faster. This way, they get up an hour before actual sunrise and get an hour extra after work. In northern and southern regions, days are considerably longer in the summer. However, in areas around the equator, the difference isn’t that much for DST to be efficient. Hence, not every country implements it.

There is a popular time module available in Python which provides functions for working with times, and for converting between representations. The function time.time() returns the current system time in ticks since 12:00am, January 3, 2021(epoch).

Many of Python’s time functions handle time as a tuple of 9 numbers, as shown below:

Leap seconds are added to make up to Earth’s slowing rotation. When DST is 0, it isn’t applied. When it’s 1, it is applied. However, when it is -1, it is up to the library to determine that.

To translate a time instant from a seconds since the epoch floating -point value into a time-tuple, pass the floating — point value to a function(e.g ., local time) that returns a time-tuple with all nine items valid.

We can format any time as per our requirement, but simple method to get time in readable format is asctime()

The calendar module gives a wide rang e of methods to play with yearly and monthly calendars. Here, we print a calendar for a given month( Jan 2021 ):

There is a popular time module available in Python which provides functions for working with times and for converting between representations.

i) time.altzone

This returns the local DST timezone’s offset. While it returns a positive value for locations west of UTC, it returns a negative value for those east of UTC.

From where we write this article, we can tell that we live east of UTC. Note that this attribute’s value does not change for a location.

ii) time.clock()

Returns the current CPU time as a floating point number of seconds. To measure computational costs of different approaches, the value of time.clock is more useful than that of time.time(). Let’s try it a few times.

iii) time.ctime([secs])

Like asctime(localtime(secs)) and without arguments is like asctime( )

iv) time.gmtime([secs])

Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the UTC time (Well, gmtime() converts the current time into UTC before returning it). Note : t.tm_isdstis always 0.

v) time.localtime([secs])

Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the localtime (t.tm_isdstis 0 or 1, depending on whether DST applies to instant secs by local rules).

vi) time.mktime([timetuple])

The mktime() method takes a time tuple as an argument, and returns the equivalent amount of ticks/seconds. It returns in floating point.

It will raise error when we call it without argument.

So, we call it with arguments.

vii) time.sleep([secs])

When called, sleep() holds the execution for a given amount of seconds. This number is passed to it as an argument.

viii) time.strftime(fmt[,tuplename])

Now what if we wanted to display the Python date and time in the format we wish to? The strftime() method takes a format and optionally, a Python time tuple, and returns the date in the format we specify. The syntax is as follows.

We can apply the following directives in the format, as per our need.

  • %a — abbreviated day of week
  • %A — full day of week
  • %b — abbreviated name of month
  • %B — full name of month
  • %c — preferred date and time representation
  • %C — century number (the year divided by 100; range 00 to 99)
  • %d — day of month (1 to 31)
  • %D — the same as %m/%d/%y
  • %e — day of month (1 to 31)
  • %g — like %G, but without the century
  • %G — 4-digit year corresponding to the ISO week number (ref. %V).
  • %h — same as %b
  • %H — hour; using a 24-hr clock (0 to 23)
  • %I — hour; using a 12-hr clock (1 to 12)
  • %j — day of year (1 to 366)
  • %m — month (1 to 12)
  • %M — minute
  • %n — newline character
  • %p — AM/PM according to given time value
  • %r — time in AM/PM representation
  • %R — time in 24-hr representation
  • %S — second
  • %t — tab
  • %T — current time; equal to %H:%M:%S
  • %u — day of week as a number (1 to 7); Monday=1
  • %U — week of year, beginning with the first Sunday as the first day of the first week
  • %V — The ISO 8601 week of year (1 to 53); week 1 is the first with at least 4 days in the current year, and with Monday as the first day of the week
  • %W — week of year; beginning with the first Monday as the first day of the first week
  • %w — day of week as a decimal; Sunday=0
  • %x — the preferred date representation without the time
  • %X — the preferred time representation without the date
  • %y — year without century (00 to 99)
  • %Y — year including century
  • %Z or %z — time zone/name/abbreviation
  • %% — a % character

Let’s try printing the shortened and full name of the month in the local time in Python.

ix) time.strptime(str[,fmt])

We just saw that the strftime() method returns a string from a format (and optionally, a tuple). The strptime() takes such a string and parses it. Finally, it returns a time tuple. It takes two arguments.

x) time.time()

Returns the current time instant, a floating -point number of seconds since the epoch.

i) time.timezone()

The timezone attribute is the same as altzone, but it does not consider the DST. Attribute time.timezone is the offset in seconds of the localtime zone (without DST) from UTC (>0 in the Americas; <0 in most of the Europe, Asia,Africa).

ii) time.tzname()

Finally, we can use this attribute to print the name of the local time zone with and without DST.

i) https://www.isip.piconepress.com

ii) https://data-flair.training/blogs/python-date-and-time/



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store