Search code examples
pythonpython-2.7datetimeunix-timestamp

How to convert unixtime to datetime by oneself


I wanna convert unixtime to datetime without using datetime.fromtimestamp.

Do you know how to create a method to convert unixtime to datetime in Python?


Solution

  • I strongly suggest you not to do that, at least until you have a wider overview over the problem set. A very naive approach might look like this (do not use this!):

    def timestamp_to_datetime(ts):
        year = 1970 + ts // (60*60*24*365)
        day_in_year = ts % (60*60*24*365) // (60*60*24)
        hour = ts % (60*60*24*365) % (60*60*24) // (60*60)
        minute = ts % (60*60*24*365) % (60*60*24) % (60*60) // 60
        second = ts % (60*60*24*365) % (60*60*24) % (60*60) % 60
    
        month = day_in_year // 30
        day = day_in_year % 30
    
        return datetime(year=year, month=month, day=day, hour=hour,
                        minute=minute, second=second)
    

    Of course, the result of this simple function is nowhere near the correct date. That we assume each month with 30 days is only the tip of the iceberg here.

    • No leap years: We're off 13 days alone because of this
    • No time zone: Was it a UTC timestamp? Local time? Which one?
    • No leap seconds: The result will be off in subtle ways
    • For negative timestamps we get negative day_in_year and directly a ValueError in the datetime() constructor. You need to handle those cases separately.
    • Things I’ve likely forgotten, because date and time are terrible things to work with and I’m glad other more competent people wrote helper libraries to be used.