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.
#!/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) try: timestamp = int(sys.argv) 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!