i am creating custom commands in django. i have a problem with conversion timestamp to date by methods like fromtimestamp. i have such error: line 13, in handle timest_conv = datetime.fromtimestamp(timest) OSError: [Errno 22] Invalid argument
this is my class with handle
class Command(BaseCommand): def handle(self, *args , **options): r = requests.get('https://api.metals.live/v1/spot/silver').json() price = r[0]['price'] timest = r[0]['timestamp'] timest_conv = datetime.fromtimestamp(timest) print(price,timest, timest_conv ) return
Advertisement
Answer
The timestamp is expressed in milliseconds since January 1st, 1970. You thus should divide these by 1’000 to retrieve the timestamp:
timest_conv = datetime.fromtimestamp(int(timest)/1000)
for the given sample timestamp, we get:
>>> datetime.fromtimestamp(1634309968403/1000) datetime.datetime(2021, 10, 15, 16, 59, 28, 403000)