24

How to get timestamp from the structure datetime? What is right alternative for non-existing datetime.utcnow().timestamp()?

1

5 Answers 5

55

use time, and int to remove the milliseconds

from time import time 

int(time())

# 1561043225
12
import time,datetime
time.mktime(datetime.datetime.today().timetuple())
1
  • 1
    Very cumbersome solution. As python. Many operations for such small work. C has time() and it works like a charm :)
    – kyb
    Sep 2, 2016 at 14:11
9

If you don't have to get timestamp from structure datetime, you can decrease instruction like this

import time
print time.time()
1
  • This construction returns the time in seconds since the epoch as a floating point number, for example: 1558442772.1057804. May 21, 2019 at 12:48
9

There is another stupid trick - achieve timedelta

(datetime.utcnow()-datetime(1970,1,1,0,0,0)).total_seconds()

found here. Better

(datetime.utcnow()-datetime.fromtimestamp(0)).total_seconds()

And this solution contains subseconds.

-3

If I understand correctly what sort of output you are seeking:

from datetime import datetime
timestamp = datetime.now().strftime("%H:%M:%S")
print(timestamp)

> 11:44:40

EDIT: Appears I misinterpreted your question? You are asking for the naive universal time, then galaxyan's answer is concise.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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