简体   繁体   中英

Convert a set datetime to epoch time

Need to convert the time 00:00:00 of each day to epoch time, below is the code I have:

import datetime
today = datetime.datetime.now()
today_morning = today.strftime('%y%m%d') + "000000"
epoch = int(today_morning.strftime('%s'))
print(epoch)

I get the following error:

AttributeError: 'str' object has no attribute 'strftime'

If anyone has any advice, please share it. I have looked around at other answers, but they seem to be for Python 2.X and for the current time, not a predetermined time. I am looking for Python 3.X answers.

I suggest you the following solution:

import datetime

today = datetime.datetime.now()
today_morning = today.replace(hour=0, minute=0, second=0, microsecond=0)
epoch = int(today_morning.timestamp())

print(epoch)

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