Skip to content

Instantly share code, notes, and snippets.

@sparkslabs
Created October 29, 2020 17:05
Show Gist options
  • Save sparkslabs/2c2c315e615225d8235479805e931dab to your computer and use it in GitHub Desktop.
Save sparkslabs/2c2c315e615225d8235479805e931dab to your computer and use it in GitHub Desktop.
A simple program to emit the current UTC time, but also renames files with the file's timestamp
#!/usr/bin/python3
import time
import sys
import os
now_timestamp = time.time()
now = time.localtime(now_timestamp)
# time.struct_time(tm_year=2017, tm_mon=1, tm_mday=10, tm_hour=15, tm_min=45, tm_sec=17, tm_wday=1, tm_yday=10, tm_isdst=0
)
name = os.path.basename(sys.argv[0])
def usage():
print ("utc - emit current time/date suitable form for scripts")
print ()
print ("Usage:")
print (" utc - emit YYYYMMDD")
print (" utc --long (utcl) - emit YYYYMMDD.HHMMSS")
print (" utc --fine (utcf) - emit YYYYMMDD.HHMMSS.sub_second_part")
print (" utc --help, -h - This help")
print ()
print ("Note sub_second relates to the instant the script is launched and is the raw")
print ("floating point part of the time")
print ()
print ("Note: utcl and utcf are aliases")
long = False
fine = False
def make_stamp(now):
fmt = "%04d%02d%02d" # Default, short
data = ( now.tm_year, now.tm_mon, now.tm_mday )
if long:
fmt = "%04d%02d%02d.%02d%02d%02d"
data = data + ( now.tm_hour, now.tm_min, now.tm_sec )
if fine:
sub_second = str(now_timestamp - int(now_timestamp))
fmt = "%04d%02d%02d.%02d%02d%02d.%s"
data = data + ( sub_second[2:], )
stamp = fmt % data
return stamp
if __name__ == "__main__":
filenames = [ x for x in sys.argv if not x.startswith("-") ][1:]
args = [ x for x in sys.argv if x.startswith("-") ]
if args:
if ("--help" in args) or ("-h" in args):
usage()
sys.exit(0)
if "--long" in args:
long = True
if "--fine" in args:
long = True
fine = True
if name == "utcl":
long = True
if name == "utcf":
long = True
fine = True
stamp = make_stamp(now)
if filenames:
for filename in filenames:
try:
x = os.stat(filename)
except OSError as e:
print (e)
continue
stamp = make_stamp(time.localtime(x.st_mtime))
print ("Rename", filename, "as", stamp+"." +filename)
os.rename(filename, stamp+"."+filename)
else:
print (stamp)
@sparkslabs
Copy link
Author

Example usage:

Given:

$ stat foo.py|grep Modify
Modify: 2019-09-27 14:48:18.552274814 +0100

Then:

$ utc
20201029

$ utc --long
20201029.171350

$ utc --fine
20201029.171357.18145465850830078

Also:

$ utc foo.py
# renames foo.py to 20190927.foo.py

$ utc --long foo.py
# renames foo.py to 20190927.144818.foo.py

$ utc --fine foo.py
# renames foo.py to 20190927.144818.7630362510681152.foo.py

$ utc *
# renames all files in a directory based on their timestamp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment