Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 344
Prometheus Avatar asked Jan 29 '26 22:01

Prometheus


2 Answers

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)
like image 155
Carlos H Romano Avatar answered Jan 31 '26 20:01

Carlos H Romano


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).

like image 26
meuh Avatar answered Jan 31 '26 20:01

meuh