Search code examples
pythonpython-datetime

Seconds since date (not epoch!) to date


I have a dataset file with a time variable in "seconds since 1981-01-01 00:00:00". What I need is to convert this time into calendar date (YYYY-MM-DD HH:mm:ss). I've seen a lot of different ways to do this for time since epoch (1970) (timestamp, calendar.timegm, etc) but I'm failing to do this with a different reference date.

I thought of doing something that is not pretty but it works:

time = 1054425600

st = (datetime.datetime(1981,1,1,0,0)-datetime.datetime(1970,1,1)).total_seconds()

datetime.datetime.fromtimestamp(st+time)

But any other way of doing this will be welcome!


Solution

  • You could try this:

    from datetime import datetime, timedelta
    
    t0 = datetime(1981, 1, 1)
    seconds = 1000000
    dt = t0 + timedelta(seconds=seconds)
    print dt
    # 1981-01-12 13:46:40
    

    Here t0 is set to a datetime object representing the "epoch" of 1981-01-01. This is your reference datetime to which you can add a timedelta object initialised with an arbitrary number of seconds. The result is a datetime object representing the required date time.

    N.B. this assumes UTC time