Last active
March 1, 2023 13:13
-
-
Save jagt/5960265 to your computer and use it in GitHub Desktop.
Naive datetime timestamp(local time treated as UTC) in Python and Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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()); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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