Skip to content

Instantly share code, notes, and snippets.

@sammchardy
Last active August 15, 2018 12:46
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sammchardy/fcbb2b836d1f694f39bddd569d1c16fe to your computer and use it in GitHub Desktop.
Save sammchardy/fcbb2b836d1f694f39bddd569d1c16fe to your computer and use it in GitHub Desktop.
Convert date to millisecond timestamp
# requires dateparser package
import dateparser
import pytz
from datetime import datetime
def date_to_milliseconds(date_str):
"""Convert UTC date to milliseconds
If using offset strings add "UTC" to date string e.g. "now UTC", "11 hours ago UTC"
See dateparse docs for formats http://dateparser.readthedocs.io/en/latest/
:param date_str: date in readable format, i.e. "January 01, 2018", "11 hours ago UTC", "now UTC"
:type date_str: str
"""
# get epoch value in UTC
epoch = datetime.utcfromtimestamp(0).replace(tzinfo=pytz.utc)
# parse our date string
d = dateparser.parse(date_str)
# if the date is not timezone aware apply UTC timezone
if d.tzinfo is None or d.tzinfo.utcoffset(d) is None:
d = d.replace(tzinfo=pytz.utc)
# return the difference in time
return int((d - epoch).total_seconds() * 1000.0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment