I have what seems like a simple question but for which I can find no straightforward answer. I would like to write a function that takes two strings as input and gives an integer as output.
In R, the function would be as simple as:
utc_seconds = function(date_string, tz) as.integer(as.POSIXct(date_string, tz = tz))
I am in control of date_string
and know the format will always be proper, e.g. 2018-02-11 00:00:00
, and I also know that tz
will always be in Olson format.
Example input/output:
utc_seconds('2018-02-11 00:00:00', tz = 'Asia/Singapore')
# 1518278400
I've looked at various combinations/permutations of datetime
, pytz
, time
, etc, to no avail. This table looked promising, but ultimately I couldn't figure out how to use it.
I've managed a "hack" as follows, but this feels inane (adding extraneous information to my input string):
from dateutil.parser import parse
from dateutil.tz import gettz
parse("2018-02-01 00:00:00 X", tzinfos={'X': gettz('Asia/Singapore')})
# datetime.datetime(2018, 2, 11, 0, 0, tzinfo=tzfile('/usr/share/zoneinfo/Asia/Singapore'))
But I can't get that to UTC time either.