Search code examples
pythonpython-3.xdatetimeunix-timestamp

How to convert a string with timezone to unix timestamp python?


I have a datetime string I get from a database and I want to convert it to unix timestamp.

I am not sure what is the way to do it.

db_timestamp = '2020-08-05 12:48:50+02:00'
f = '%Y-%m-%d %H:%M:%S%z'
timestamp = datetime.strptime(db_timestamp , f)
TypeError: strptime() argument 1 must be str, not datetime.datetime 

Another way I tried was as following

python_timestamp = datetime.isoformat(db_timestamp)
test_timestamp = datetime.strptime(python_timestamp , f)

Then I get the following error

ValueError: time data '2020-08-05T12:48:50+02:00' does not match format '%Y-%m-%d %H:%M:%S%z'

How to fix this error? What should be the correct string format for db_timestamp?


Solution

  • assuming you run Python 3.7 or higher, what you want is fromisoformat to parse the string and timestamp() to get seconds since the epoch UNIX time (POSIX).

    from datetime import datetime
    db_timestamp = '2020-08-05 12:48:50+02:00'
    # to datetime object:
    dt = datetime.fromisoformat(db_timestamp)
    # to UNIX time:
    ts = dt.timestamp()
    print(repr(dt), ts)
    >>> datetime.datetime(2020, 8, 5, 12, 48, 50, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200))) 1596624530.0