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
JavaScript
x
10
10
1
class Command(BaseCommand):
2
def handle(self, *args , **options):
3
r = requests.get('https://api.metals.live/v1/spot/silver').json()
4
price = r[0]['price']
5
timest = r[0]['timestamp']
6
timest_conv = datetime.fromtimestamp(timest)
7
print(price,timest, timest_conv )
8
9
return
10
Advertisement
Answer
The timestamp is expressed in milliseconds since January 1st, 1970. You thus should divide these by 1’000 to retrieve the timestamp:
JavaScript
1
1
1
timest_conv = datetime.fromtimestamp(int(timest)/1000)
for the given sample timestamp, we get:
JavaScript
1
3
1
>>> datetime.fromtimestamp(1634309968403/1000)
2
datetime.datetime(2021, 10, 15, 16, 59, 28, 403000)
3