w3resource

Python: Find out what the epoch is on a given platform

Python Datetime: Exercise-55 with Solution

The epoch is the point where time starts, and is platform dependent. For Unix, the epoch is January 1, 1970, 00:00:00 (UTC). Write a Python program to find out what the epoch is on a given platform. Convert a given time in seconds since the epoch.

Sample Solution:

Python Code:

# Import the time module
import time

# Print a message indicating the epoch on a given platform
print("\nEpoch on a given platform:")
# Print the time structure representing the epoch (January 1, 1970, 00:00:00 UTC)
print(time.gmtime(0))

# Print a message indicating time in seconds since the epoch
print("\nTime in seconds since the epoch:")
# Print the time structure representing 36000 seconds after the epoch
print(time.gmtime(36000))

Output:

Epoch on a given platform:
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)

Time in seconds since the epoch:
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=10, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

Explanation:

In the exercise above,

  • The code imports the "time" module
  • It prints a message indicating the epoch on a given platform.
  • It uses the "time.gmtime()" function to convert the time in seconds since the epoch to a time structure representing UTC time.
    • In the first "print" statement, "time.gmtime(0)" represents the time structure for the epoch, i.e., January 1, 1970, 00:00:00 UTC.
  • It prints a message indicating the time in seconds since the epoch.
  • It again uses the "time.gmtime()" function to convert the time in seconds (36000 seconds) since the epoch to a time structure representing UTC time.
    • In the second "print" statement, "time.gmtime(36000)" represents the time structure for 36000 seconds after the epoch.

Flowchart:

Flowchart: Find out what the epoch is on a given platform.

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program to set the default timezone used by all date/time functions.
Next: Write a Python program to get time values with components using local time and gmtime

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/date-time-exercise/python-date-time-exercise-55.php