How do I get seconds since 1/1/1970 of a Python datetime object?
Asked Answered
P

5

7

I'm using Python 3.7 and Django. I wanted to get the number of seconds (or milliseconds) since 1/1/1970 for a datetime object. Following the advice here -- In Python, how do you convert a `datetime` object to seconds?, I implemented

now = datetime.now()
...
return [len(removed_elts) == 0, score, now.total_seconds()]

but the "now.total_seconds()" line is giving the error

AttributeError: 'datetime.datetime' object has no attribute 'total_seconds'

What's the right way to get the seconds since 1/1/1970?

Petes answered 3/9, 2019 at 14:25 Comment(1)
I think you are only having a problem because you didn't subtract the datetime objects to get a timedelta object (which does have an attribute total_seconds). I believe that this answer on the question you linked does what you want. But you can also use datetime.timestamp as mentioned below.Storebought
S
5
now = datetime.now()
...
return [len(removed_elts) == 0, score, now.timestamp()]
Stryker answered 3/9, 2019 at 14:29 Comment(0)
H
3

This should work.

import datetime
first_date = datetime.datetime(1970, 1, 1)
time_since = datetime.datetime.now() - first_date
seconds = int(time_since.total_seconds())
Hosea answered 3/9, 2019 at 14:29 Comment(4)
Are "time_since" and "first_date" different object types?Petes
they're bot datetime objects. @PetesHosea
no it doesn't "01" isn't recognized by the interpreter should be: datetime(1970, 1, 1) insteadLanyard
You're correct, I've edited my answer. But after editing the answer, they do return datetime objects, and that was his question. @LanyardHosea
L
2
import time
print(time.time())

Output:

1567532027.192546
Lisp answered 3/9, 2019 at 14:34 Comment(0)
M
2

In contrast to the advice you mentioned, you don't call total_seconds() on a timedelta object but on a datetime object, which simply doesn't have this attribute.

So, one solution for Python 3.7 (and 2.7) could for example be:

import datetime

now = datetime.now()
then = datetime.datetime(1970,1,1)
...
return [len(removed_elts) == 0, score, (now - then).total_seconds()]

Another shorter but less clear (at least on first sight) solution for Python 3.3+ (credits to ababak for this one):

import datetime

now = datetime.now()
...
return [len(removed_elts) == 0, score, now.timestamp()]
Marchpane answered 3/9, 2019 at 14:53 Comment(0)
S
1

You can try:

import datetime

now = datetime.datetime.now()
delta = (now - datetime.datetime(1970,1,1))
print(delta.total_seconds())

now is of type datetime.datetime and has no .total_seconds() method.

delta is of type datetime.timedelta and does have a .total_seconds() method.

Hope this helps.

Sacci answered 3/9, 2019 at 14:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.