Date to String to Pyhton conversion

Asked

Viewed 123 times

2

I’m trying to get a date of this next select in python

select MAX(PAYMENT_DATE) from fact_cashflow
WHERE DOCUMENT_ID = 'SALDO FINAL' and PAYMENT_AMOUNT > 0

But my answer on the console is this

(datetime.date(2017, 2, 1),)

I would like the date to be formatted in '2017-02-01'

How do I do?

2 answers

3

You can use the .strftime('%Y-%m-%d')

In this way:

t = datetime.date(2017, 2, 1)
t.strftime('%Y-%m-%d')

Your answer will be: '2017-02-01'

  • This is the correct way: convert the date at the time of submission to the user in Python. In the accepted answer, what comes from the database is a string, and all the advantages of Python datetime objects are lost: comparisons, distance to other dates, can be used again on another object, etc...

2


The function date_format allows formatting the date returned in the Mysql database query:

select date_format(MAX(PAYMENT_DATE), '%Y-%m-%d') from fact_cashflow
WHERE DOCUMENT_ID = 'SALDO FINAL' and PAYMENT_AMOUNT > 0;
  • Thank you very much, I got it here.

  • The best is almost always to let Python read a database datetime object - and turn from datetime to string with the method strftime only at the point of the application that generates the output for the user. A datetime object is much more useful within the program’s logic.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.