Convert Epoch Time with Python

I’m slowly improving my Python skills, mostly by Googling and combining multiple answers to code a solution to my systems administration tasks. Today I decided to write a simpe converter that takes Epoch Time as a parameter and returns you the time and date it corresponds to.

datetime and timezone Modules in Python

Most of the functionality is done using the fromtimestamp function of the datetime module. But because I also like seeing time in UTC, I decided to use timezone module as well.

epoch.py script

#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3

import sys
from datetime import datetime, timezone

if len(sys.argv)>1:
  print ("This is the Epoch time: ", sys.argv[1])

  try:
      timestamp = int(sys.argv[1])

      if timestamp>0:
        timedate = datetime.fromtimestamp(timestamp)
        timedate_utc = datetime.fromtimestamp(timestamp, timezone.utc)

        print ("Time/date: ", format(timedate))
        print ("Time/date in UTC: ", format(timedate_utc))
  except ValueError:
        print ("Timestamp should be a positive integer, please.")
else:
  print ("Usage: epoch.py <EPOCH-TIMESTAMP>")

FIXME: I’ll revisit this to re-publish script directly from GitHub.

Here’s how you can use the script:

greys@maverick:~/proj/python $ ./epoch.py 1566672346
 This is the Epoch time:  1566672346
 Time/date:  2019-08-24 19:45:46
 Time/date in UTC:  2019-08-24 18:45:46+00:00

I implemented basic checks:

  • script won’t run if no command line parameters are passed
  • an error message will be shown if command line parameter isn’t a number (and therefore can’t be a timestamp)

Do you see anything that should be changed or can be improved? Let me know!

See Also




Contact Me

Follow me on Facebook, Twitter or Telegram:
Recommended
I learn with Educative: Educative
IT Consultancy
I'm a principal consultant with Tech Stack Solutions. I help with cloud architectrure, AWS deployments and automated management of Unix/Linux infrastructure. Get in touch!
Recent Articles
03 Sep 2024

macOS Sequoia 15.0

02 Sep 2024

Video: Has This Worked Before?

24 Mar 2024

Homelab: Mac Pro 2013 32GB

Recent Tweets