How can I get the local date and time in Django?
I tried this solution. But it works only for the date now.
from django.utils import timezone
now = timezone.localtime(timezone.now()) #OK
date = timezone.localtime(timezone.date()) #Error
time = timezone.localtime(timezone.time()) #Error
Preferably in the same format as for datetime
now = datetime.datetime.now() #'2020-04-28 17:57:34.120383'
date = datetime.datetime.now().date() #'2020-04-28
time = datetime.datetime.now().time() #18:12:08.987472
Extract the date and time from the local instant object.
from django.utils import timezone
now = timezone.localtime(timezone.now())
date = now.date()
time = now.time()
Related
I need to get the number of days since a file was created, and i tried this code:
import os.path, time
import datetime
from datetime import date
path = 'D:/Reg.txt'
creation_date = "created: %s" % time.ctime(os.path.getctime(path))
today = datetime.datetime.today()
delta = today - creation_date
print(delta.days)
but i get this error message: unsupported operand type(s) for -: 'datetime.datetime' and 'str'
In your code, creation_date was a string. To make it workable, convert it to a datetime object using the datetime.fromtimestamp(epochtime) from datetime library. Example below:
import os.path, time
import datetime
from datetime import date
path = 'D:/Reg.txt'
creation_date = datetime.datetime.fromtimestamp(os.path.getctime(path))
today = datetime.datetime.today()
delta = today - creation_date
print(delta.days)
Note that datetime.datetime.fromtimestamp converts a number to a datetime object so you just need to pass in the epoch time directly. In your case, this was os.path.getctime(path)
You should convert creation date into datetime format from string
import os.path, time
import datetime
from datetime import date
from datetime import datetime
path = 'D:/Reg.txt'
creation_date = "created: %s" % time.ctime(os.path.getctime(path))
creation_date=datetime.strptime(creation_date, '%m-%d-%Y').date()
today = datetime.datetime.today()
delta = today - creation_date
print(delta.days)
I want to get current time in GMT, like 2015-08-21 05:13:13+00:00 Here you can see that correction is made like 00:00 for GMT, In django they are using from django.utils import timezone and date_to = timezone.now() to calculate the current time. How I will get the same functionality in flask, Formate of time should be like 2015-08-21 05:13:13+00:00 not like 2015-03-30 07:19:06.746037+02. I got this link but they are using 2015-03-30 07:19:06+02. I don't want. Just GTM time
Following code is in Django, I want same in Flask, Here they are using from django.utils import timezone. In Flask what is equivalent of it, which gives current time in this format 2015-08-21 05:13:13+00:00
import datetime
import pytz
from django.utils import timezone
def calc_date_args(date_from, date_to, date_options):
try:
date_to = timezone.now()
print 'calc_date_args, date_to', date_to #calc_date_args, date_to 2015-08-21 05:13:13.615541+00:00
date_from = date_to - datetime.timedelta(days=float(date_options))
except Exception:
raise ValueError(_("The time delta must be a number representing "
"the time span in days"))
return date_from, date_to
Not sure if you mean UTC time instead of GMT, as most machines consume UTC and most timestamps are in UTC.
In Python 3 to get UTC timezone-aware timestamp:
import datetime
def now():
"""Get timezone-aware UTC timestamp."""
return datetime.datetime.now(datetime.timezone.utc)
I am trying to all the record for a certain day with the following:
entered_at = request.session['entered_at']
entered_at = datetime.strptime(entered_at, "%m-%d-%Y")
day_start = entered_at.replace(hour=00, minute=00)
day_end = entered_at.replace(hour=23, minute=59)
entries = Entry.objects.filter(
customer=customer,
entered_at__lt=day_end,
entered_at__gte=day_start
)
When I do this I get the following warning in my console:
DateTimeField received a naive datetime while time zone support is
active.
I know I can add something like: , day_start = entered_at.replace(hour=00, minute=00, tzinfo=<UTC>)
however, this will not make the range from midnight to 11:59pm relative to the users timezone if I use UTC.
How can I express a full day relative to the users timezone?
I believe you want something like this, using the pytz library. See How to make an unaware datetime timezone aware in python:
import pytz
entered_at = request.session['entered_at']
entered_at = datetime.strptime(entered_at, "%m-%d-%Y")
day_start = entered_at.replace(hour=00, minute=00)
day_end = entered_at.replace(hour=23, minute=59)
timezone = pytz.timezone("America/Los_Angeles")
day_start = timezone.localize(day_start)
day_end = timezone.localize(day_end)
entries = Entry.objects.filter(customer=customer,
entered_at__lt=day_end,
entered_at__gte=day_start)
Say I have a model:
Mymodel(models.Model):
endtimestamp = models.DateTimeField(null=True)
I need a query to get all Mymodel objects with endstimestamp between today's midnight and yesterday midnight.
what have I tried:
today = datetime.datetime.today()
todays_midnigh = datetime.datetime.fromtimestamp(
today.strftime('%Y-%m-%d 00:00:00.0')
)
yesterday_midnight = todays_midnight - datetime.timedelta(days=1)
objs = Mymodel.objects.filter(endtimestamp__range(
yesterday_midnight, todays_midnight)
)
But this line todays_midnigh = datetime.datetime.fromtimestamp(today.strftime('%Y-%m-%d 00:00:00.0')) does not work, and I know there must be a much pythonic and clear way of achieving this.
assumming this from datetime import datetime as dt, do that:
today = dt.today()
todays_midnigh = dt.combine(today,dt.max.time())
or
todays_midnigh = dt.combine(today,dt.min.time())
as appropriate
I'm attempting to craft a function that takes a time object and converts it to UTC time. The code below appears to be off by one hour. When i run noon through the converter, i get back 18:00:00. But when i run the same data through online converters, i get 17:00:00.
What am i doing wrong here? Any help would be greatly appreciated.
import pytz, datetime
def convert_to_utc(time, tz):
now_dt = datetime.datetime.utcnow()
#get a date object
date_dt = now_dt.date()
#combine the current date object with our given time object
dt = datetime.datetime.combine(date_dt, time)
#get an timezone object for the source timezone
src_tz = pytz.timezone(str(tz))
#stamp the source datetime object with the src timezone
src_dt = dt.replace(tzinfo=src_tz)
#get the offset from utc to given timezone
offset = str(int(src_dt.strftime("%z"))).rstrip('0')
#convert the source datetime object to
utc_dt = src_dt.astimezone(pytz.utc)
#return the converted time and the offset in integer format
return (utc_dt.time(), int(offset))
time = datetime.datetime.strptime('12:00:00', "%H:%M:%S").time()
(TIME, offset) = convert_to_utc(time, 'America/Chicago')
print TIME.strftime("%H:%M:%S")
**EDIT**
Here's the updated(and functional) code in case anyone else needs help converting to/from UTC.
Thanks everyone for your help!
import pytz, datetime
def convert_to_utc(time, tz): #this returns the offset in int form as well
now_dt = datetime.datetime.utcnow()
#get a date object
date_dt = now_dt.date()
#combine the current date object with our given time object
dt = datetime.datetime.combine(date_dt, time)
#get an timezone object for the source timezone
src_tz = pytz.timezone(str(tz))
#stamp the source datetime object with the src timezone
src_dt = src_tz.localize(dt)
#get the offset from utc to given timezone
offset = str(int(src_dt.strftime("%z"))).rstrip('0')
#convert the source datetime object to
utc_dt = src_dt.astimezone(pytz.utc)
#return the converted time and the offset in integer format
return (utc_dt.time(), int(offset))
def convert_from_utc(time, tz):
now_dt = datetime.datetime.now()
date = now_dt.date()
dt = datetime.datetime.combine(date, time)
dest = pytz.timezone(str(tz))
dt = dt.replace(tzinfo=pytz.utc)
dest_dt = dt.astimezone(dest)
return dest_dt.time()
time = datetime.datetime.strptime('12:00:00', "%H:%M:%S").time()
(TIME, offset) = convert_to_utc(time, 'America/Chicago')
print TIME.strftime("%H:%M:%S")
utc_time = datetime.datetime.strptime('17:00:00', "%H:%M:%S").time()
TIME = convert_from_utc(utc_time, 'America/Chicago')
print TIME.strftime("%H:%M:%S")
Change
src_dt = dt.replace(tzinfo=src_tz)
to
src_dt = src_tz.localize(dt)
Using localize adjusts for Daylight Savings Time, while replace does not.
See the section entitled "Localized times and date arithmetic" in the docs.
To convert time in given timezone to UTC time:
from datetime import datetime
import pytz
def convert_to_utc(time, tzname, date=None, is_dst=None):
tz = pytz.timezone(tzname)
if date is None: # use date from current local time in tz
date = datetime.now(tz).date()
dt = tz.localize(datetime.combine(date, time), is_dst=is_dst)
return dt.astimezone(pytz.utc).time(), dt.utcoffset().total_seconds()
if is_dst is None it raises an exception for ambiguous local times.
To convert UTC time to local time in given timezone:
def convert_from_utc(time, tzname, date=None):
tz = pytz.timezone(tzname)
if date is None: # use date from current time in utc
date = datetime.utcnow().date()
dt = datetime.combine(date, time).replace(tzinfo=pytz.utc)
return tz.normalize(dt.astimezone(tz)).time()
Example:
time = datetime.strptime('12:00:00', "%H:%M:%S").time()
utc_time, offset = convert_to_utc(time, 'America/Chicago')
print utc_time.strftime("%H:%M:%S"), offset # -> 17:00:00 -18000.0
utc_time = datetime.strptime('17:00:00', "%H:%M:%S").time()
time = convert_from_utc(utc_time, 'America/Chicago')
print time.strftime("%H:%M:%S") # -> 12:00:00
In general it is preferable to work with full datetime objects to avoid ambiguity with what is the correct date i.e., pass and return datetime objects.
By using the replace method on the datetime, you're not allowing the time zone to be adjusted for daylight savings time. Try using one of the documented methods from the pytz documentation:
src_dt = src_tz.localize(dt)