Skip to content

Instantly share code, notes, and snippets.

@jagt
Last active March 1, 2023 13:13
Show Gist options
  • Save jagt/5960265 to your computer and use it in GitHub Desktop.
Save jagt/5960265 to your computer and use it in GitHub Desktop.
Naive datetime timestamp(local time treated as UTC) in Python and Javascript
// convert a date to timestamp as if it is a UTC date
// in other words used to remove local timezone info and fake everything as UTC
// must beware the funky api naming
// workaround js UTC date things
// the general rule is treat date as naive datetime with no timezone info
// using UTC timezone is better since it won't change based on user's computer location
function asUTCTimestamp(date) {
return Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(),
date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());
}
function asUTCDate(ts) {
// not sure how this can work really
var date = new Date(ts);
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),
date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds());
}
from calendar import timegm
def asUTCTimestamp(d):
''' convert a date to timestamp as if it is a UTC date
in other words used to remove local timezone info and fake everything as UTC
notice that it should be * 1000 to match the Javascript timestamp
'''
# `timegm` is making UTC timestamp rather than local.
# see `man timegm` for info
return timegm(d.timetuple());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment