Python datetime strptime

Posted under » MySQL » Python on 20 Mar 2024

MySQL datetime looks like this 2024-03-19 21:07:55.118494. Problem is when you want to do a datetime compare you can't because all you have is string. So you need to import datetime and convert the string into a python datetime format.

from datetime import datetime
for dog in query:
        akhir = dog.created
        tday = datetime(2024,3,16,0)
        if akhir > tday :
            print(akhir)

Another example Django API

Sometime you need to strip away (strptime) the time from datetime and just leave the date data.

from datetime import datetime

format_data = "%Y-%m-%d %H:%M:%S.%f"

for x in p391:
    query = (quiz_question_log
             .select().where(quiz_question_log.created > '2024-08-01', 
                             quiz_question_log.test_id == 4)
             .order_by(quiz_question_log.id.asc())).limit(1)
    for dog in query :
        dogdate = datetime.strptime(str(dog.endate), format_data)
        print(dog.user_id, "You have done nothing!", dogdate.date() )

If you just want to see the time, you change the param as dogdate.time()

The traditional way to calculate the days between date is

from datetime import date

d0 = date(2024, 8, 24)
d1 = date(2024, 9, 4)
diff = d1 - d0
print(diff.days)

For information on datetime — Basic date and time types library.

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data