我从JSON文件导入数据,其日期格式如下1/7/11 9:15
为了接受这个日期,最好的变量类型/格式是什么?如果不是最有效的方法来完成这项任务呢?
感谢。
答案 0 :(得分:1)
“为了接受这个日期而定义的最佳变量类型/格式是什么?”
“如果不是最有效的方法来完成这项任务?”
您应该使用Python内置datetime
库中的the datetime.strptime
方法:
>>> from datetime import datetime
>>> import json
>>> json_datetime = "1/7/11 9:15" # still encoded as JSON
>>> py_datetime = json.loads(json_datetime) # now decoded to a Python string
>>> datetime.strptime(py_datetime, "%m/%d/%y %I:%M") # coerced into a datetime object
datetime.datetime(2011, 1, 7, 9, 15)
# Now you can save this object to a DateTimeField in a Django model.
答案 1 :(得分:0)
如果你看一下https://docs.djangoproject.com/en/dev/ref/models/fields/#datetimefield,就会说django使用的是python datetime库,它是在http://docs.python.org/2/library/datetime.html发布的。
这是一个工作示例(包含许多调试打印和逐步说明:
from datetime import datetime
json_datetime = "1/7/11 9:15"
json_date, json_time = json_datetime.split(" ")
print json_date
print json_time
day, month, year = map(int, json_date.split("/")) #maps each string in stringlist resulting from split to an int
year = 2000 + year #be ceareful here! 2 digits for a year may cause trouble!!! (could be 1911 as well)
hours, minutes = map(int, json_time.split(":"))
print day
print month
print year
my_datetime = datetime(year, month, day, hours, minutes)
print my_datetime
#Generate a json date:
new_json_style = "{0}/{1}/{2} {3}:{4}".format(my_datetime.day, my_datetime.month, my_datetime.year, my_datetime.hour, my_datetime.minute)
print new_json_style