0

I've got a DateTimeField(auto_now_add=True) in my model. However, I wish to update this field, and the format I'm receiving from my API is a UNIX timestamp. Can I somehow convert the format I receive from my API to the correct one? (eg 1640206232 to 2021-12-22 20:50:32).

Using postgres as my db if that matters..

erikvm
  • 858
  • 10
  • 30

1 Answers1

1

Yes As mentioned by @Sevy in his comment you can use the following

from datetime import datetime

timestamp = 1640206232 
dt_object = datetime.fromtimestamp(timestamp, tz='UTC') # Or whatever timezone you want

print("dt_object =", dt_object)
print("type(dt_object) =", type(dt_object))

More info and how to convert the other way can be found here: https://www.programiz.com/python-programming/datetime/timestamp-datetime

  • 1
    Thanks for the solution. Forgot to add that I'd like to have it offset-aware, since I plan on comparing it with a `timezone.now()` value – erikvm Dec 23 '21 at 07:58
  • Maybe check this article: https://stackoverflow.com/questions/32325209/python-how-to-convert-unixtimestamp-and-timezone-into-datetime-object – Johan Martinson Dec 23 '21 at 08:32