2

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?

3
  • in your example, db_timestamp has a date/time string in another format as you show in the ValueError - which one is it actually? Both formats are ISO 8601 compatible, so fromisoformat will work (see my answer). Commented Sep 3, 2020 at 11:01
  • 1
    You should get different errors (or in a different order) than you have shown. I get the last error for the first code sample. Commented Sep 3, 2020 at 11:01
  • Which Python 3.x version are you using? (what is x?) Commented Sep 3, 2020 at 11:03

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

@jmf: glad I could help. one more thing, be aware that if your input string does not contain a UTC offset, Python will assume that it is local time (your OS setting) - the resulting UNIX timestamp then considers the local time's UTC offset.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.