简体   繁体   中英

Python REST API date format

I am working on a Python REST API project where I need to retrieve data from a database. the database table has timestamp column since the data needs to be record many times per day. Here is a part of the code below.

In this piece of code, I need the API to show me the data of the current day (instead of a certain date).

import requests
import datetime

# Using python requests library, set up GET request
payload = {'date1' : 'CURDATE()', 'date2' : 'CURDATE() + INTERVAL 1 DAY'}

# Send GET request to REST API
r = requests.get('http://localhost:8080/data', params=payload)

# Decode the JSON result of the GET request
rows = r.json()

# Loop through data and format the date string
for i in rows:
    i[0] = datetime.datetime.fromtimestamp(i[0]).strftime('%Y-%m-%d %H:%M:%S')
print rows

In date1 and date 2 part, I used to use a certain date like 2013-12-30 and 2013-12-31, the program will return all the data from 2013-12-30. Right now when I try to ask the program to return whatever the data from the current day, the program gives me a blank result [] .

The code needs to talk to a database, but I doubt the problem comes from the database part. Hope everyone can help me. Thanks!

Generate your dates in your Python code instead of passing arbitrary SQL functions to your database for execution, which is very dangerous.

>> import datetime
>> today = datetime.date.today()
>> tomorrow = today + datetime.timedelta(days=1)
>> print today
2013-12-31
>> print tomorrow
2014-01-01

Now you can pass today and tomorrow as date strings (eg str(today) or '{0}'.format(today) to your web service.

As noted in the comments, your service is not RESTful. You may want to read up on REST before going much further.

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