Skip to content

Instantly share code, notes, and snippets.

@hectorcanto
Last active June 14, 2018 13:48
Show Gist options
  • Save hectorcanto/a3a33a5a767fbb3f7de611e7bceeb37e to your computer and use it in GitHub Desktop.
Save hectorcanto/a3a33a5a767fbb3f7de611e7bceeb37e to your computer and use it in GitHub Desktop.
[Datetime utils] Datetime & timestamp utils for Python #py3 #datetime # utils
def dt2ts(dt: Optional[datetime]) -> Optional[int]:
return int(time.mktime(dt.timetuple())) if dt is not None else None
def dt2ts_ms(dt: Optional[datetime]) -> Optional[int]:
return dt2ts(dt) * 1000 if dt is not None else None
def ts2dt(ts: Optional[int]) -> Optional[datetime]:
return datetime.utcfromtimestamp(int(ts)) if ts is not None else None
def ts_ms2dt(ts: Optional[int]) -> Optional[datetime]:
return ts2dt(int(ts/1000) if ts is not None else None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment