1

I have the following function:

epoch = datetime(1970, 1, 1)

def epoch_seconds(date):
    """Returns the number of seconds from the epoch to date."""
    print(epoch)
    td = date - epoch
    return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)

When I take a date directly from my model I get the following error:

print(epoch_seconds(self.modified))

can't subtract offset-naive and offset-aware datetimes

So I checked the format of both self.modified and epoch

self.modified = 2015-08-13 16:29:37.601681+00:00
epoch = 1970-01-01 00:00:00

I think I understand the error and need these to be in the same format however, I have no idea what .601681+00:00 is and how to do this. Could some help to explain the what is after the . and how to get these to match?

2 Answers 2

8

After the dot, there's the timezone information, which, for this situation, I don't believe you need. Just go ahead and get rid of that timezone info this way:

date = date.replace(tzinfo=None)
1

If you have a datetime object you can get the seconds from the epoch from it directly:

d = datetime.datetime(2015,1,1)
print int(d.strftime("%s"))

In your question, .601681 is extra resolution in the time, in microseconds, and +00:00 is the offset in hours:minutes from UTC (previously GMT).

1
  • This solution doesn't works in python 3. In Python 3.3+ you can use timestamp() instead:
    – matabares
    Jul 31, 2017 at 2:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.