简体   繁体   English

如何在python中将日期时间转换为纪元?

[英]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. 我应该使用哪种格式来执行以下操作,以便可以json呈现。 "2016-10-14 14:34:14+00:00". “ 2016-10-14 14:34:14 + 00:00”。 I am using python 2.7 and django 1.10 我正在使用python 2.7和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() : 选项1,您可以使用isoformat()

from datetime import datetime

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

Option 2, strftime() , do not confuse it with strptime : 选项2, strftime() ,不要将其与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. 实际上在datego datetime对象中,按以下方式在纪元中进行了转换。

Emample 1 范例1

import datetime

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

Example 2 例子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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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