db.Time Property saving time as datetime instead of just time - python

I am using db.time property to save time required for a conversion:
my_model.conversion_time = time_taken = datetime.datetime.strptime(str(conversion_end - conversion_start), "%H:%M:%S.%f").time()
but when i see the data in datastore viewer , it is stored as datetime object with date of 1970-01-01. Does anybody know how I can just save the time in the datastore

I'm not sure why you have two inline assignments, but to get time out of a timedelta object:
>>> b
datetime.datetime(2013, 7, 15, 10, 21, 31, 599402)
>>> a
datetime.datetime(2013, 7, 15, 10, 18, 11, 251477)
>>> str(b-a)
'0:03:20.347925'
>>> (datetime.datetime.min + (b-a)).time()
datetime.time(0, 3, 20, 347925)
In order to store only the time, you need to use TimeProperty in your datastore. It will be represented internally as datetime, but will store datetime.time() objects.

Related

How to get time object of current time in datetime library python

I need to get the current date and time upon running the program, both as their respective objects in the datetime library.
I have been able to get a date object for the current date fine:
datetime.date.today()
but how can i get a time object for the current time? datetime.time.now() doesn't work, and datetime.time() is used to instantiate a time object by passing in your own values, but i want to just get a time object with the current time information.
>>> import datetime
>>> n = datetime.datetime.now()
>>> n
datetime.datetime(2020, 8, 23, 12, 37, 51, 595180)
>>> n.date()
datetime.date(2020, 8, 23)
>>> n.time()
datetime.time(12, 37, 51, 595180)

Difference between the time objects in python?

What is the difference between the 2 statements:
import datetime
print datetime.datetime.now()
datetime.datetime(2015, 1, 28, 12, 32, 9, 762118)
from datetime import *
>> datetime.time(datetime.now())
datetime.time(12, 33, 3, 693084)
Actually I want to compare TimeField of a django model with the current day's 1 hour less time. My code snippet for the same:
Mymodel.objects.filter(
follow_up_date=datetime.datetime.now().date,
# commented now
# preferred_time__lt=(
# datetime.datetime.now() - datetime.timedelta(hours=1)),
preferred_time__lt=(datetime.time(datetime.now()) - datetime.timedelta(hours=1)),
)
Mymodel:
class Mymodel(models.Model):
follow_up_date = models.DateField("Follow up Date",null=True,blank=True)
preferred_time = models.TimeField(_("Preferred time"),default=now,
null=True,blank=True)
I am trying to extract all the instances which are scheduled for the day, whose preferred time has elapsed just 1 hour back. Which should be the correct filter for the 'preferred_time'? I got wrong results for the commented code. I am not clear.
This is a cron job i.e management command to be run every 1 hour in django
In the first instance:
datetime.datetime(2015, 1, 28, 12, 32, 9, 762118)
You have a datetime object. It has both the date (first three numbers) and the time (last four numbers).
The second object you mention:
datetime.time(12, 33, 3, 693084)
This is just the time component.
To compare a TimeField, you need just the time component; for a DateField, just the date component.
In your code, you have the following datetime.datetime.now().date this is just the name of the built-in function date. You need to call it:
>>> datetime.datetime.now().date
<built-in method date of datetime.datetime object at 0xb74ac9b0>
>>> datetime.datetime.now().date()
datetime.date(2015, 1, 28)
You also cannot do datetime.time(datetime.datetime.now()), datetime.time() is a constructor method, it is not a way to covert other objects.
You also cannot subtract timedelta from a time object:
To get the correct result, you need to subtract one hour from the datetime object, then convert it to time:
>>> (datetime.datetime.now() - datetime.timedelta(hours=1)).time()
datetime.time(9, 27, 16, 93746)
In the end, your filter would look like:
filter_date = datetime.datetime.now().date()
filter_time = (datetime.datetime.now() - datetime.timedelta(hours=1)).time()
Mymodel.objects.filter(follow_up_date=filter_date,
preferred_time__lt=filter_time)
datetime.now() given date and time information.
datetime.time() give only time information.
e.g
>>> from datetime import *
>>> datetime.now()
datetime.datetime(2015, 1, 28, 12, 52, 35, 164500)
>>> datetime.time(datetime.now())
datetime.time(12, 52, 41, 97521)
>>>

Python time conversion

I have some timestamp data from a database and I need to convert it to a Python datetime (in tuple format). How can I do that?
For instance, I need to convert 2013-04-16 16:31:35.649+05:30 format to datetime(2013, 4, 16, 16, 31, 35).
I am trying to do the, Django, new user registration part of the project and whenever the user submits the data and registers then he gets an verification email but whenever the user clicks the verification link then, it produces the following error:
can't compare offset-naive and offset-aware datetimes
from dateutil import parser
dt = parser.parse("2013-04-16 16:31:35.649+05:30")
# dt == datetime.datetime(2013, 4, 16, 16, 31, 35, 649000, tzinfo=tzoffset(None, 19800))
dt.astimezone(pytz.utc).replace(tzinfo=None)
returns datetime.datetime(2013, 4, 16, 11, 1, 35, 649000) which is the same instant in UTC and without tzinfo (offset-naive).
If you want to store datetime objects without tzinfo, then store it in UTC.
Large parts of the world use daylight saving time, which makes some offset-naive datetimes ambiguous. UTC does not have these problems.

Convert Long Int Timestamp to Date/Time

I use connect the sqlite3 of chrome 'History' file for analysis. But there are data for last_visit_time, which is timestamp, but I don't know how to change it to real time.
I test like this:
2012-04-18 23:22:11.084300 (utctime)
2012-04-19 01:22:11.084300 (myPC time)
12,979,264,931,952,304 (the time stamp in the data)
I printed the utctime and clicked a website, almost at the same time. So I get the statistic like above. 12,979,264,931,952,304 is the long int, so normal way to convert is not possible.
How can I convert the timestamp to a date?
The timestamp it stores is the number of microseconds since midnight UTC on January 1st, 1601. To convert this to the current time, you can add the number of microseconds you have to the epoch date, with help from this answer, like this:
>>> import datetime
>>> epoch_start = datetime.datetime(1601, 1, 1)
>>> delta = datetime.timedelta(microseconds=12979264931952304)
>>> epoch_start + delta
datetime.datetime(2012, 4, 18, 23, 22, 11, 952304)
To convert to your local timezone, you can use this method (note that I am currently UTC - 4, while it looks like you are UTC + 2):
>>> from dateutil import tz
>>> from_zone = tz.tzutc()
>>> to_zone = tz.tzlocal()
>>> utc_time = (epoch_start + delta).replace(tzinfo=from_zone)
>>> utc_time.astimezone(to_zone)
datetime.datetime(2012, 4, 18, 19, 22, 11, 952304, tzinfo=tzlocal())

How do you convert a naive datetime to DST-aware datetime in Python?

I'm currently working on the backend for a calendaring system that returns naive Python datetimes. The way the front end works is the user creates various calendar events, and the frontend returns the naive version of the event they created (for example, if the user selects October 5, 2020 from 3:00pm-4:00pm, the frontend returns datetime.datetime(2020, 10, 5, 15, 0, 0) as the start and datetime.datetime(2011, 10, 5, 16, 0, 0) as the end.
What I need to do is to take the naive datetime and convert it into UTC for storage in a database. Each user of the system has already specified their timezone preference, so the naive datetime is considered to be of the same timezone as their timezone preference. Obviously the datetimes need to be stored relative to UTC so that if users change their timezone, existing events will still render at the correct time that they scheduled them.
The frontend is outside my control, so I can't change the data that I'm receiving. The database design is also outside my control, so I can't change what data is being stored and how.
Here is the approximate approach I have taken so far:
import pytz
def convert_to_UTC(naive_datetime, user_tz_preference):
user_datetime = naive_datetime.replace(tzinfo=user_tz_preference)
utc_datetime = user_datetime.astimezone(pytz.utc)
The problem I ran into is related to Daylight Savings Time:
>>> from datetime import datetime
>>> import pytz
>>> user_tz_preference = pytz.timezone('US/Pacific')
>>> naive_datetime = datetime(2011, 10, 26, 12, 0, 0)
>>> user_datetime = naive_datetime.replace(tzinfo=user_tz_preference)
>>> user_datetime
datetime.datetime(2011, 10, 26, 12, 0, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>)
>>> received_utc = user_datetime.astimezone(pytz.utc)
>>> received_utc
datetime.datetime(2011, 10, 26, 20, 0, tzinfo=<UTC>)
>>> expected_utc = datetime(2011, 10, 26, 19, 0, tzinfo=pytz.utc)
>>> expected_utc == received_utc
False
Notice that using 'replace' sets the timezone to PST instead of PDT regardless of the date, which gives it a UTC offset of 8 hours instead of the expected 7 hours DST offset, so the time ends up being saved incorrectly.
What options do I have for converting the naive datetime to the correct PDT (or other timezone-relative DST) tzinfo?
(Also, please note that not all users live in a timezone that observes DST, or may live in a timezone that switches over at different times, so in order to do a solution like a timedelta correction before saving, I would need to know if the timezone supports DST, and on which dates it switches over).
Pytz's localize function can do this: http://pytz.sourceforge.net/#localized-times-and-date-arithmetic
from datetime import datetime
import pytz
tz = pytz.timezone('US/Pacific')
naive_dt = datetime(2020, 10, 5, 15, 0, 0)
utc_dt = tz.localize(naive_dt, is_dst=None).astimezone(pytz.utc)
# -> 2020-10-05 22:00:00+00:00
With zoneinfo from Python 3.9's standard lib:
from datetime import datetime
from zoneinfo import ZoneInfo
naive_datetime = datetime(2011, 10, 26, 12, 0, 0)
user_tz_preference = ZoneInfo("America/Los_Angeles") # former US/Pacific
# it is safe to replace the tzinfo:
user_datetime = naive_datetime.replace(tzinfo=user_tz_preference)
# ...or set it directly:
user_datetime = datetime(2011, 10, 26, 12, tzinfo=ZoneInfo("America/Los_Angeles"))
# astimezone works as before:
utc_datetime = user_datetime.astimezone(ZoneInfo("UTC"))
print(repr(user_datetime))
# datetime.datetime(2011, 10, 26, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='US/Pacific'))
print(user_datetime.isoformat())
# 2011-10-26T12:00:00-07:00
print(utc_datetime.isoformat())
# 2011-10-26T19:00:00+00:00
docs

Categories