SoFunction
Updated on 2025-03-01

How to handle datetime in Django (strftime/strptime)

strftime<Convert date, datetime,() type processing to string type>

The strftime() function is a function used to format a date, datetime, and time. It supports classes such as date, datetime, time, etc., and uses formatting characters to represent these times as strings.

import datatime
()

or

from datatime import datatime
()

My output conversion format

strftime('%Y-%m-%d %H:%I:%S')

The effect is similar to 2018-07-02 23:18:20.

strptime<Convert string processing to data of the expected type>

The strptime() function converts the date and time represented by the string into the corresponding date and time according to the formatted string requirements.

d2 = ('2018-03-02 17:41:20', '%Y-%m-%d %H:%M:%S')

The format of the conversion comparison:

Convert to string

%y Double digit year representation (00-99)
%Y Four-digit year representation (000-9999)
%m Month (01-12)
%d One day in the month (0-31)
%H 24-hour hours (0-23)
%I 12-hour hours (01-12) 12-hour hours
%M Minutes (00=59)
%S seconds (00-59)

Two bugs encountered:

1: Display time and database inconsistent bug:

I once encountered such a problem, the time fetched from the database is inconsistent with the front-end display time. Later, after more information converted from output time is generated, I finally found that because my colleague who wrote the code before used this

one['time'] = one['time'].strftime('%Y-%m-%d %H:%I:%S')

%I is a twelve-hour conversion form. When converting the format in this way, although there will be no errors, the output results will be inconsistent with the database. The database records time in 24 hours.

Two:(2018, 2, 2, 18, 25, 29, tzinfo=<UTC>) is not JSON serializable

Such an error message appears...

(2018, 2, 2, 18, 25, 29, tzinfo=<UTC>) is not JSON serializable

This is an error message that appears when placing the datetime data directly in json. It cannot be placed directly in json.

The solution is: you can use strftime for serialization, such as the following method

.strftime("%Y-%m-%d %H:%M:%S")

Let's take a look at the specific explanation of Python:time, strftime and strptime

The most commonly used() returns a floating point number in seconds. But the type handled by strftime is time.struct_time, which is actually a tuple. Both strptime and localtime return this type.

>>> import time
>>> t = ()
>>> t
1202872416.4920001
>>> type(t)
<type 'float'>
>>> t = ()
>>> t
(2008, 2, 13, 10, 56, 44, 2, 44, 0)
>>> type(t)
<type 'time.struct_time'>
>>> ('%Y-%m-%d', t)
'2008-02-13'
>>> ('2008-02-14', '%Y-%m-%d')
(2008, 2, 14, 0, 0, 0, 3, 45, -1)

totalKnot

The above is the method of handling datetime in Django (strftime/strptime) introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!