Difference between the time objects in python? - 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)
>>>

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)

Python: How to Drop Hours from a Datetime? [duplicate]

I have a date string and want to convert it to the date type:
I have tried to use datetime.datetime.strptime with the format that I want but it is returning the time with the conversion.
when = alldates[int(daypos[0])]
print when, type(when)
then = datetime.datetime.strptime(when, '%Y-%m-%d')
print then, type(then)
This is what the output returns:
2013-05-07 <type 'str'>
2013-05-07 00:00:00 <type 'datetime.datetime'>
I need to remove the time: 00:00:00.
print then.date()
What you want is a datetime.date object. What you have is a datetime.datetime object. You can either change the object when you print as per above, or do the following when creating the object:
then = datetime.datetime.strptime(when, '%Y-%m-%d').date()
If you need the result to be timezone-aware, you can use the replace() method of datetime objects. This preserves timezone, so you can do
>>> from django.utils import timezone
>>> now = timezone.now()
>>> now
datetime.datetime(2018, 8, 30, 14, 15, 43, 726252, tzinfo=<UTC>)
>>> now.replace(hour=0, minute=0, second=0, microsecond=0)
datetime.datetime(2018, 8, 30, 0, 0, tzinfo=<UTC>)
Note that this returns a new datetime object -- now remains unchanged.
>>> print then.date(), type(then.date())
2013-05-07 <type 'datetime.date'>
To convert a string into a date, the easiest way AFAIK is the dateutil module:
import dateutil.parser
datetime_object = dateutil.parser.parse("2013-05-07")
It can also handle time zones:
print(dateutil.parser.parse("2013-05-07"))
>>> datetime.datetime(2013, 5, 7, 1, 12, 12, tzinfo=tzutc())
If you have a datetime object, say:
import pytz
import datetime
now = datetime.datetime.now(pytz.UTC)
and you want chop off the time part, then I think it is easier to construct a new object instead of "substracting the time part". It is shorter and more bullet proof:
date_part datetime.datetime(now.year, now.month, now.day, tzinfo=now.tzinfo)
It also keeps the time zone information, it is easier to read and understand than a timedelta substraction, and you also have the option to give a different time zone in the same step (which makes sense, since you will have zero time part anyway).
For me, I needed to KEEP a timetime object because I was using UTC and it's a bit of a pain. So, this is what I ended up doing:
date = datetime.datetime.utcnow()
start_of_day = date - datetime.timedelta(
hours=date.hour,
minutes=date.minute,
seconds=date.second,
microseconds=date.microsecond
)
end_of_day = start_of_day + datetime.timedelta(
hours=23,
minutes=59,
seconds=59
)
Example output:
>>> date
datetime.datetime(2016, 10, 14, 17, 21, 5, 511600)
>>> start_of_day
datetime.datetime(2016, 10, 14, 0, 0)
>>> end_of_day
datetime.datetime(2016, 10, 14, 23, 59, 59)
If you specifically want a datetime and not a date but want the time zero'd out you could combine date with datetime.min.time()
Example:
datetime.datetime.combine(datetime.datetime.today().date(),
datetime.datetime.min.time())
You can use simply pd.to_datetime(then) and pandas will convert the date elements into ISO date format- [YYYY-MM-DD].
You can pass this as map/apply to use it in a dataframe/series too.
You can usee the following code:
week_start = str(datetime.today() - timedelta(days=datetime.today().weekday() % 7)).split(' ')[0]

Display Python datetime without time

I have a date string and want to convert it to the date type:
I have tried to use datetime.datetime.strptime with the format that I want but it is returning the time with the conversion.
when = alldates[int(daypos[0])]
print when, type(when)
then = datetime.datetime.strptime(when, '%Y-%m-%d')
print then, type(then)
This is what the output returns:
2013-05-07 <type 'str'>
2013-05-07 00:00:00 <type 'datetime.datetime'>
I need to remove the time: 00:00:00.
print then.date()
What you want is a datetime.date object. What you have is a datetime.datetime object. You can either change the object when you print as per above, or do the following when creating the object:
then = datetime.datetime.strptime(when, '%Y-%m-%d').date()
If you need the result to be timezone-aware, you can use the replace() method of datetime objects. This preserves timezone, so you can do
>>> from django.utils import timezone
>>> now = timezone.now()
>>> now
datetime.datetime(2018, 8, 30, 14, 15, 43, 726252, tzinfo=<UTC>)
>>> now.replace(hour=0, minute=0, second=0, microsecond=0)
datetime.datetime(2018, 8, 30, 0, 0, tzinfo=<UTC>)
Note that this returns a new datetime object -- now remains unchanged.
>>> print then.date(), type(then.date())
2013-05-07 <type 'datetime.date'>
To convert a string into a date, the easiest way AFAIK is the dateutil module:
import dateutil.parser
datetime_object = dateutil.parser.parse("2013-05-07")
It can also handle time zones:
print(dateutil.parser.parse("2013-05-07"))
>>> datetime.datetime(2013, 5, 7, 1, 12, 12, tzinfo=tzutc())
If you have a datetime object, say:
import pytz
import datetime
now = datetime.datetime.now(pytz.UTC)
and you want chop off the time part, then I think it is easier to construct a new object instead of "substracting the time part". It is shorter and more bullet proof:
date_part datetime.datetime(now.year, now.month, now.day, tzinfo=now.tzinfo)
It also keeps the time zone information, it is easier to read and understand than a timedelta substraction, and you also have the option to give a different time zone in the same step (which makes sense, since you will have zero time part anyway).
For me, I needed to KEEP a timetime object because I was using UTC and it's a bit of a pain. So, this is what I ended up doing:
date = datetime.datetime.utcnow()
start_of_day = date - datetime.timedelta(
hours=date.hour,
minutes=date.minute,
seconds=date.second,
microseconds=date.microsecond
)
end_of_day = start_of_day + datetime.timedelta(
hours=23,
minutes=59,
seconds=59
)
Example output:
>>> date
datetime.datetime(2016, 10, 14, 17, 21, 5, 511600)
>>> start_of_day
datetime.datetime(2016, 10, 14, 0, 0)
>>> end_of_day
datetime.datetime(2016, 10, 14, 23, 59, 59)
If you specifically want a datetime and not a date but want the time zero'd out you could combine date with datetime.min.time()
Example:
datetime.datetime.combine(datetime.datetime.today().date(),
datetime.datetime.min.time())
You can use simply pd.to_datetime(then) and pandas will convert the date elements into ISO date format- [YYYY-MM-DD].
You can pass this as map/apply to use it in a dataframe/series too.
You can usee the following code:
week_start = str(datetime.today() - timedelta(days=datetime.today().weekday() % 7)).split(' ')[0]

Django objects queryset filter by matching datetime

I have a model with a field name 'timestamp' that is a datetime field, and when I print them in python manage.py shell I get:
>>> a.timestamp
datetime.datetime(2013, 7, 15, 18, 45, tzinfo=<UTC>)
Now.... I am running django celery task every 30 seconds that suppose to retrieve all the matching objects in the last 30 seconds.
how can I do it (thing = MyModelName.objects.filter(.. something ..)
I hope that I manage to explain my self.
Thank you all in advanced.
Update:
When I am typing in my server (python shell)
datetime.datetime.now()
I am getting
datetime.datetime(2013, 7, 15, 20, 34, 4, 366166)
MyModelName.objects.filter(timestamp__gte=(datetime.datetime.now() - datetime.timedelta(seconds=30)))
import datetime
from datetime import timedelta
time = datetime.datetime.now()
delta = timedelta(seconds=30)
newtime = time + delta #after adding 30 sec with current time
so you can loop through the (newtime - time) time interval then you can
get the expected result.

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

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.

Categories