简体   繁体   中英

Python - Convert 12 hour time in UTC in epoch format

I have a text box that displays time in following local time format - 04/03/2018 02:59:44 PM I'm using Selenium in python to get this time and convert it (local time) to epoch time (UCT). But it's converting to a time that is 11 hours 30 mins earlier (April 3, 2018 3:29:44 AM). here is my code:

next_chk_dt = myDriver.find_element_by_xpath("(//input[@id='dateIDVisible'])[6]").get_attribute('value')
# displays 04/03/2018 02:59:44 PM if you print the value
temp_Time2 = datetime.datetime.strptime(next_chk_dt, '%m/%d/%Y %H:%M:%S %p')
epoch_Time1 = calendar.timegm(temp_Time2.timetuple())
print (epoch_Time1)
# You get 1522726184, which is incorrect. it should be 1522781984 

calendar.timegm() converts from UTC to seconds since epoch.

mktime() converts from local time to seconds since epoch.

source: https://docs.python.org/2/library/time.html

I was able to resolve this based on the suggestion above

from time import strptime
from datetime import datetime
mytm= ("04/03/2018 02:59:44 PM")
fmt = ("%m/%d/%Y %I:%M:%S %p")
epochDate = int(time.mktime(time.strptime(mytm, fmt)))
print (epochDate)
# ==> 1522781984

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