1

I am trying to convert an epoch timestamp to datetime.

I have tried using datetime.fromtimestamp but it gives me an invalid argument error.

Here is my code:

def get_last_login(name):
    url = f"https://api.hypixel.net/player?key={API_KEY}&name={name}"
    res = requests.get(url)
    data = res.json()
    if data["player"] is None:
        return None

    lastlogouttime = (data["player"]["lastLogout"])
    timedate = datetime.fromtimestamp(lastlogouttime)
    return format(timedate)

lastlogouttime returns an epoch timestamp from the hypixel api.

Edit: Full traceback:

Ignoring exception in command lastlogin:
Traceback (most recent call last):
  File "C:\Users\Deagan\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\Deagan\Desktop\hybot\bot.py", line 46, in lastlogin
    lastlogin = hypixelcustomwrapper.get_last_login(name)
  File "C:\Users\Deagan\Desktop\hybot\hypixelcustomwrapper.py", line 74, in get_last_login
    timedate = datetime.fromtimestamp(lastlogouttime)
OSError: [Errno 22] Invalid argument

Import statement:

from datetime import datetime, timezone

What it gets from the api:

"lastLogout":1589588947970"

What it should return:

1589588947970
halfer
  • 19,824
  • 17
  • 99
  • 186
Deagan Muir
  • 103
  • 4
  • 13
  • 1
    Can you add the full error traceback, and an example of the value you get for `lastlogouttime`? Also, what does your `import` statement look like? The correct way to use the `fromtimestamp` function is `datetime.datetime.fromtimestamp()` is you're using `import datetime`. – Prateek Dewan May 16 '20 at 17:15
  • @PrateekDewan done. – Deagan Muir May 16 '20 at 17:27
  • 2
    Try `timedate = datetime.fromtimestamp(lastlogouttime/1000)`? The value seems to be in milliseconds, whereas the function takes seconds as input. This is answered here: https://stackoverflow.com/questions/37494983/python-fromtimestamp-oserror – Prateek Dewan May 16 '20 at 17:31
  • @PrateekDewan Thank you! it worked. it outputs ```2020-05-15 17:29:07.970000``` how can i remove everything after 17:29? – Deagan Muir May 16 '20 at 17:36
  • `datetime.fromtimestamp(lastlogouttime/1000).strftime('%Y-%m-%d %H:%M')` – Prateek Dewan May 16 '20 at 17:40

0 Answers0