Wednesday, 20 July 2022

django, python3 time, timedelta

 https://www.geeksforgeeks.org/python-datetime-timedelta-function/

https://miguendes.me/how-to-use-datetimetimedelta-in-python-with-examples

1) A timedelta object denotes a duration, it can also represent the difference between two dates or times.

We can use this object to add to or subtract a duration from a date, and it defines its constructor as datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

It is used in python3 to add/subtract date :

# Timedeltafunction demonstration
 
from datetime import datetime, timedelta
 
 
# Using current time
ini_time_for_now = datetime.now()
 
# printing initial_date
print ("initial_date", str(ini_time_for_now))
 
# Calculating future dates
# for two years
future_date_after_2yrs = ini_time_for_now + \
                        timedelta(days = 730)
 
future_date_after_2days = ini_time_for_now + \
                         timedelta(days = 2)
 
# printing calculated future_dates
print('future_date_after_2yrs:', str(future_date_after_2yrs))
print('future_date_after_2days:', str(future_date_after_2days))


2) python3 time zone
first specify time zonein settings.py for your project
TIME_ZONE = 'Europe/Brussels'
USE_TZ = True

in your views, 
from django.utils import timezone

timezone.now() will give you UTC time at the moment for the timezone specified in settings.py

to get your timezone for the time at moment use :
timezone.localtime(timezone.now())

https://stackoverflow.com/questions/39953166/django-utils-timezone-now-returns-utc-in-default-timefield

No comments:

Post a Comment