getting proper date format from SQL search results (datetime.datetime)

烂漫一生 提交于 2021-01-28 11:57:34

问题


This is my first time using cx_oracle. Part of my project is to create a search engine that processes "SELECT FROM.." queries and displays them. This is for searching patient information and the tests he/she have been prescribed. I thought it would also be a good idea to return prescribe dates for tests.

Here is what I execute:

searchPatientName = "SELECT b.PATIENT_NO, a.NAME, c.TEST_NAME, b.TEST_DATE, b.RESULT FROM patient a, test_record b, test_type c WHERE b.TYPE_ID = c.TYPE_ID AND b.PATIENT_NO = a.HEALTH_CARE_NO AND a.NAME = :patient_name"

patientName = "Vera Fuselier"
search.execute(searchPatientName, patient_name=patientName)

rows = search.fetchall()                    
for row in rows:
    print(row)
break

The output I am getting is what I want for the project, but the date is not what I am wanting.

 (100103, 'Vera Fuselier', 'Blood Test', datetime.datetime(2012, 8, 30, 0, 0), 'Normal')
 (100103, 'Vera Fuselier', 'MRI', datetime.datetime(2014, 11, 30, 0, 0), 'Sclerosis')

Please notice how the date is not displaying the way I want to (with datetime.datetime), and I can't figure out a way to fix this.

I've been using this to no avail: getting date fields from oracle in correct format using Python and cx-oracle

How can I get the date to display in a format like: '12-08-30' for example?


回答1:


datetime is the date object of python, with that you could get any format you want in your case you can get your format with:

import datetime
row[3].strftime('%y-%m-%d')

Now for clarification of what is happening. With strftime() you can get a Date or Time String out of your Datetimeobject. with '%y-%m-%d' I formated it.

row[3] should be your dateobject element.

%y returns the Year with 2 digits like 14 for 2014. If you want the whole year you have to type %Y

%m returns the number of month and %d the number of day.

there are also options like weekday, the name of the month, etc.

you can read about that in the docs

So now your code should look like this:

import datetime

#your code to read the file

for row in rows:
    row[3] = row[3].strftime('%y-%m-%d')
    print(row)

#some other code


来源:https://stackoverflow.com/questions/26857253/getting-proper-date-format-from-sql-search-results-datetime-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!