post-thumb

Datetime in python

In this tutorial we will learn all about datetime in python and diffrent conversion according to requirements in various scenario.

from django.utils import timezone
print(timezone.now())
print(timezone.now().date())

The strftime() function is used to convert DateTime object into easily readable string format.

from datetime import datetime

# current date and time
now = datetime.now()

now.strftime("%d/%m/%Y, %H:%M:%S")
# '21/12/2022, 16:15:41'

Format Codes

%a  -Sun, Mon...

%A - Sunday, Monday

%d  -01, 02, 03...

%-d  -1, 2, 3...

%b - Jan, Feb

%B  -January, February

%m  -01, 02 ...

%-m  -1, 2....

%y - 00, 01

%-y - 0, 1

%Y  -2005, 2006

%H  -00, 01 (24 Hour)

%-H  -0, 1 (24 Hour)

%I  -01, 02 (12 hour)

%-I  -1, 2 (12 hour)

%p  -Am, Pm

 

Specify datetime from the 7 minutes of now.

from django.db import models
from django.utils import timezone


def default_expiry_time():
    return timezone.now() + timezone.timedelta(minutes=7)


class Mymodel(models.Model):
    expires_on = models.DateTimeField(default=default_expiry_time)