0

I am trying to convert unix time to human readable time in python and am either getting an error, or the date:1969-12-31 18:00:00.

When I run:

    datetime.datetime.fromtimestamp((1540254404.9600408)).strftime('%Y-%m-%d %H:%M:%S')

I am getting error:

[Errno 22] Invalid argument

I have also tried a few other functons like:

time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(1540254404.9600408)))

which returns: '1969-12-31 18:00:00', which is also not correct...

my unix value as noted above is: 1540254404.9600408

MattG
  • 1,682
  • 5
  • 25
  • 45

1 Answers1

2

This is what I just did, and it works fine! Using Python 3.5.2, Pycharm, Mint18. Same result with 2.7.12.

from datetime import *

print(datetime.fromtimestamp((1540254404.9600408)).strftime('%Y-%m-%d %H:%M:%S'))

The printed result is: 2018-10-22 20:26:44. Remove one of the "datetime" in your code. No need to reference datetime twice.

Or if you do the import differently:

import datetime

print(datetime.datetime.fromtimestamp((1540254404.9600408)).strftime('%Y-%m-%d %H:%M:%S'))

The same applies for your second line of code:

import time

print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(1540254404.9600408))))

Another note, time.timestamp is a float, not an int.

Nic3500
  • 8,144
  • 10
  • 29
  • 40
  • 1
    If you just do `import datetime` then you have to write `datetime` twice. The two methods are equivalent. If he weren't naming the function properly he'd get a different error. – Barmar Oct 23 '18 at 00:45