kyb
kyb

Reputation: 8131

Get timestamp in seconds from python's datetime

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

Upvotes: 29

Views: 75284

Answers (5)

Alex
Alex

Reputation: 6037

use time, and int to remove the milliseconds

from time import time 

int(time())

# 1561043225

Upvotes: 66

kyb
kyb

Reputation: 8131

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.

Upvotes: 10

Konchshell
Konchshell

Reputation: 112

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.

Upvotes: -3

Damotorie
Damotorie

Reputation: 596

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

import time
print time.time()

Upvotes: 9

galaxyan
galaxyan

Reputation: 6111

import time,datetime
time.mktime(datetime.datetime.today().timetuple())

Upvotes: 12

Related Questions