Skip to content

Instantly share code, notes, and snippets.

@ranjitiyer
Last active February 3, 2019 16:15
Show Gist options
  • Save ranjitiyer/039698734e64b90d03fc2b37352fdc16 to your computer and use it in GitHub Desktop.
Save ranjitiyer/039698734e64b90d03fc2b37352fdc16 to your computer and use it in GitHub Desktop.
python dates
time.asctime([t])
t is response of gmtime() or localtime()
time.clock()
time.clock_gettime(clk_id) > float
time.clock_gettime_ns(clk_id) > float
# Returns the response in this format
time.ctime([secs]) > secs since epoch
>> 'Sun Jan 27 20:40:07 2019'
# Returns a structure
time.gmtime()
>> time.struct_time(tm_year=2019, tm_mon=1, tm_mday=28, tm_hour=4, tm_min=40, tm_sec=59, tm_wday=0, tm_yday=28, tm_isdst=0)
# Returns a structure
time.localtime()
>> time.struct_time(tm_year=2019, tm_mon=1, tm_mday=27, tm_hour=20, tm_min=42, tm_sec=4, tm_wday=6, tm_yday=27, tm_isdst=0)
# Sleep
time.sleep(secs)
# Convert time to a format
time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
>> '2019-01-28 04:43:49'
# Return the time in secs since epoch time as float
time.time()
>> 1548650688.857249
# Create a time from an incoming string
tz = '2019-01-28T04:43:49Z'
format = '%Y-%m-%dT%H:%M:%SZ'
time_struct=time.strptime(tz, format)
>> time.struct_time(tm_year=2019, tm_mon=1, tm_mday=28, tm_hour=4, tm_min=43, tm_sec=49, tm_wday=0, tm_yday=28, tm_isdst=-1)
# Create a string representation of time
time.strftime("%Y-%m-%d",time_struct)
'2019-01-28'
# Create a date representation from timestamp
>>> time.time()
1548651332.1780329
>>> datetime.date.fromtimestamp(time.time())
datetime.date(2019, 1, 27)
# Read time as string as datetime
start=datetime.datetime.strptime("2018-01-01 00:00:00Z", "%Y-%m-%d %H:%M:%SZ")
# Apply math on it
delta_30_mins = datetime.timedelta(minutes=30)
start = end - delta_30_min
# Concurrency with thread pools
from concurrent import futures
def task(input):
return "result"
def done_callback(fn: futures.Future):
print(type(fn))
if fn.cancelled():
print("Task was cancelled")
if fn.done():
error = fn.exception()
if error:
print(error)
else:
print(fn.result())
pool = futures.ThreadPoolExecutor(max_workers=1)
future = pool.submit(task, "input")
future.add_done_callback(done_callback)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment