datetime.datetime.timestamp()
is what you're looking for (relevant part):
For aware datetime instances, the return value is computed as:
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
Example:
import datetime
now = datetime.datetime.now()
epoch = now.timestamp()
# 1542394106.155199
Implemented into your example, we'll have to use another approach as datetime.datetime.strptime()
doesn't quite take timezone kindly due to a bug (relevant question where I found the info). So we'll have to use another builtin to parse it (example here):
from dateutil.parser import parse
mytime = "2018-11-12 00:30:20.000 EST"
dt = parse(mytime)
epoch = dt.timestamp()
The parsed string is still a datetime.datetime
object so you can handle it the same after parsing.
Note: however parse
might complain it read the timezone but not understood it:
UnknownTimezoneWarning: tzname EDT identified but not understood. Pass `tzinfos` argument in order to correctly return a timezone-aware datetime. In a future version, this will raise an exception.
You might end up needing to pass the tzinfos
into the parse()
method anyhow:
from dateutil.parser import parse
# from dateutil.tz import gettz # <-- can use if you know the tz to retrieve
tzinfos = {'EST': -18000, 'CET': +3600}
# another example: {"CST": gettz("America/Chicago")}
mytime = "2018-11-12 00:30:20.000 EST"
dt = parse(mytime, tzinfos=tzinfos)
epoch = dt.timestamp()
print(epoch)
So I guess in the end it's not as simple as you might want.