简体   繁体   中英

how to convert date-time to epoch in python?

I want this particular date-time to be converted to epoch but it is giving me format error. what format should i use to do the following so that it can be json rendered. "2016-10-14 14:34:14+00:00". I am using python 2.7 and django 1.10

stra = "instance[0].Timing"
formata = "%Y-%m-%d %H:%M:%S+00:00"
timing = calendar.timegm(time.strptime(stra, formata))
     return HttpResponse(json.dumps(
           {'result': 'True'
            'timing': timing,
            }))

Option 1, you can use isoformat() :

from datetime import datetime

print(datetime.utcnow().isoformat())
# '2016-10-19T03:39:40.485521'

Option 2, strftime() , do not confuse it with strptime :

print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S+00:00'))
# '2016-10-19 03:42:58+00:00'

Actually in django datetime object are converted in epoch as following way.

Emample 1

import datetime

current_date = datetime.datetime.now()
epoch = int(current_date.strftime("%s")) * 1000

Example 2

import datetime
date_object = datetime.datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')
epoch = int(date_object.strftime("%s")) * 1000

This is a literal string, it's not pulling data out of whatever instance you have:

stra = "instance[0].Timing"

Perhaps you meant the following instead?

stra = instance[0].Timing

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