简体   繁体   中英

add 2 hours in current time in Python and print the time in timestamp

How to get the current time and return that in timestamp format after adding 2 hours in it like 1535020200000

i tried the following but I am not getting the expected result

current_time + timedelta(hours=2)

(datetime.now()).split('.')[0] + timedelta(hours=2)

since the second one returns a string, addition operation cannot be done

I would recommend the following

from datetime import datetime, timedelta
two_hours_from_now = datetime.now() + timedelta(hours=2)
print(two_hours_from_now.timestamp())

如果需要时间戳,请使用time.time

current_plus_2_hours = time.time() + 2 * 60 * 60

You can do as follow:

import datetime


current_time = datetime.datetime.now()

later = current_time + datetime.timedelta(hours=2)

print(later.timestamp())

You get:

 1535031690.031316

Quoting the documentation :

Return POSIX timestamp corresponding to the datetime instance. The return value is a float similar to that returned by time.time() .

thanks to all of you, though this worked for me

start_at = 2
hours_from_now = int(str(time.time() + start_at * 60 * 60)[0:10]) * 1000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM