Home > Net >  How to get the UNIX time from datetime string with timezone in Python 2.7
How to get the UNIX time from datetime string with timezone in Python 2.7

Time:11-25

I want to get the UNIX timestamp from a datetime string, for example '2021-11-20T12:42:00-08:00'. I googled the solution for this, but not found the answer.

CodePudding user response:

using python-dateutil this is trivial

from dateutil.parser import parse
dt = parse('2021-11-20T12:42:00-08:00')
timestamp = dt.timestamp()

# in py2.7 you cannot use .timestamp so the following should work
import pytz
timestamp = time.mktime(dt.astimezone(pytz.utc).timetuple()) 
  • Related