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?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
jmf
  • 356
  • 5
  • 25
  • 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](https://en.wikipedia.org/wiki/ISO_8601) compatible, so `fromisoformat` will work (see my answer). – FObersteiner Sep 03 '20 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. – mkrieger1 Sep 03 '20 at 11:01
  • Which Python 3.x version are you using? (what is x?) – mkrieger1 Sep 03 '20 at 11:03

1 Answers1

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
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • 1
    @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. – FObersteiner Sep 04 '20 at 09:22