I need to print (and pass to an external API) the current datetime in the following format:
DD-MM-YYYY:HH:MM:SS:SSS
where the last 3 SSS
imply milliseconds. I know how to print the current datetime up to microseconds using Python's strftime
as in the below manage.py shell
Django shell session:
In [1]: from django.utils import timezone
In [2]: timezone.now()
Out[2]: datetime.datetime(2013, 8, 5, 15, 26, 10, 71046, tzinfo=<UTC>)
In [3]: timezone.now().strftime('%d-%m-%Y:%H:%M:%S:%f')
Out[3]: '05-08-2013:15:28:31:647504'
How to print the ending :SSS
part so that the above string becomes:
'05-08-2013:15:28:31:123'
ie displaying milliseconds (using only 3 digits) rather than microseconds?
Add the milliseconds separately by dividing the timestamp microseconds by 1000:
tznow = timezone.now()
'{:%d-%m-%Y:%H:%M:%S}.{:03d}'.format(tznow, tznow.microsecond // 1000)
Demo:
>>> from django.utils import timezone
>>> tznow = timezone.now()
>>> '{:%d-%m-%Y:%H:%M:%S}.{:03d}'.format(tznow, tznow.microsecond // 1000)
'05-08-2013:15:36:00.339'
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.