bysucpmeti bysucpmeti - 2 months ago 11
JSON Question

How can I convert from Datetime to Milliseconds in Django?

I want to convert date (ex: 2016-09-20 22:00:00+00:00) to milliseconds. I will apply this block:

def get_calendar_events(request):

user = request.user
taken_course = Course.objects.get_enrollments(user=user)

homework_list = []
for course in taken_course:
homework_list = course.get_homeworks()

data_l = []
for homework in homework_list:

data_l.append({
"id": user.id,
"title": homework.title,
"class": "event-important",
"start": homework.start_date, # Milliseconds
"end": homework.end_date # Milliseconds
})

data = {
"success": 1,
"result": [data_l]
}
return JsonResponse(data, safe=False)


I need to edit "start" and "end" tags in data_l. Thank you.

Answer

In python 3, you can use timestamp() method to get the number seconds elapsed since Jan 1, 1970.

import datetime
d=datetime.datetime.now()
print d.timestamp()
# 1474450000.164866

This is assuming the homework.start_date field is a datetime object.