Thursday, 4 January 2024

python django datetime cast and comparions

 list of dateime usage:

https://pynative.com/python-compare-dates/


datetime now in django will return current time with specified timezone in settings.py, if nothing specified it will return utc

https://stackoverflow.com/questions/10783864/django-1-4-timezone-now-vs-datetime-datetime-now

>>> from django.utils import timezone
>>> import datetime
>>> print timezone.now()
def now():
    """
    Returns an aware or naive datetime.datetime, depending on settings.USE_TZ.
    """
    if settings.USE_TZ:
        # timeit shows that datetime.now(tz=utc) is 24% slower
        return datetime.utcnow().replace(tzinfo=utc)
    else:
        return datetime.now()

timezone.now() returns a timezone object based on server timezone in settings.py
 but it is time unaware
settings.py
# TIME_ZONE = 'UTC'
TIME_ZONE = os.environ.get('TZ', 'UTC')
USE_I18N = True

USE_TZ = False
//
use pytz plugin to make it time aware
https://pypi.org/project/pytz/
from datetime import datetime, timedelta
import pytz
from pytz import timezone
for instance:
        now_obj = datetime.now().astimezone(timezone('US/Pacific'))
        yesterday_obj = datetime.now() + timedelta(days=-1)
// conver timeaware string into datetime aware obj
            #  tz aware string  2024-01-05T23:42:45.000000Z)
            #.000Z is handled using %fZ 
https://stackoverflow.com/questions/214777/how-do-you-convert-yyyy-mm-ddthhmmss-000z-time-format-to-mm-dd-yyyy-time-forma
           
 timeaware= datetime.strptime(timeware, '%Y-%m-%dT%H:%M:%S.%fZ')
   timeaware= timeaware.astimezone(timezone('US/Pacific'))
now can compare 
timeaware < now_obj

 INFO  date time obj is 2024-01-04 16:38:20.886187-08:00
INFO date time yesterday obj is 2024-01-03 16:38:20.918589
 INFO date time token expires  is 2024-01-05 23:50:26-08:00

!!!important
https://stackoverflow.com/questions/14619494/how-to-understand-strptime-vs-strftime

strptime means string parser, this will convert a string format to datetime.

strptime means string parser, this will convert a string format to datetime.

Example:-

datetime.strptime('2019-08-09 01:01:01', "%Y-%m-%d %H:%M:%S")

datetime.datetime(2019, 8, 9, 1, 1, 1)//Result

strftime means string formatter, this will format a datetime object to string format.


No comments:

Post a Comment