I'm trying to do something like this:
time() + timedelta(hours=1)
however, Python doesn't allow it, apparently for good reason.
Does anyone have a simple work around?
Related:
What is the standard way to add N seconds to datetime.time in Python?
The solution is in the link that you provided in your question:
datetime.combine(date.today(), time()) + timedelta(hours=1)
Full example:
from datetime import date, datetime, time, timedelta
dt = datetime.combine(date.today(), time(23, 55)) + timedelta(minutes=30)
print dt.time()
Output:
00:25:00
If it's worth adding another file / dependency to your project, I've just written a tiny little class that extends datetime.time with the ability to do arithmetic. If you go past midnight, it just wraps around:
>>> from nptime import nptime
>>> from datetime import timedelta
>>> afternoon = nptime(12, 24) + timedelta(days=1, minutes=36)
>>> afternoon
nptime(13, 0)
>>> str(afternoon)
'13:00:00'
It's available from PyPi as nptime ("non-pedantic time"), or on GitHub: https://github.com/tgs/nptime
The documentation is at http://tgs.github.io/nptime/
Workaround:
t = time()
t2 = time(t.hour+1, t.minute, t.second, t.microsecond)
You can also omit the microseconds, if you don't need that much precision.
This is a bit nasty, but:
from datetime import datetime, timedelta
now = datetime.now().time()
# Just use January the first, 2000
d1 = datetime(2000, 1, 1, now.hour, now.minute, now.second)
d2 = d1 + timedelta(hours=1, minutes=23)
print d2.time()
You can change time() to now() for it to work
from datetime import datetime, timedelta
datetime.now() + timedelta(hours=1)
A little bit late to the party but you can also do something along the lines of:
init_time = time(4,0)
added_time = 8
new_time = datetime.time(init_time.hour+added_time)
Note that you'll need to add in correction code to make sure init+time.hour + added+time do not go above 23,59.
Related
I have a time from five minutes ago, using datetime.time.now() and I need to know what the time would be if I subtracted that time from the current time.
Try 1 - Didn't Work:
from datetime import datetime, timedelta
time1 = datetime.now()
time2 = datetime.now() + timedelta(minutes=5)
print(time1 - time2)
This gave me "-1 day, 23:54:59.999987".
Try 2 - Worked, but is there a better way?:
time1 = datetime.now()
time2 = datetime.now() + timedelta(minutes=5)
print(str(time1 - time2).split(',')[1])
This gave me the desired result, but is there a method besides string manipulation?
You wanted to take an advice how to use a time object?
Well, if you want to specify a format of string representation of your time, just use strftime
Example below:
from datetime import datetime, timedelta
time1 = datetime.now()
time2 = datetime.now() + timedelta(minutes=5)
print((time1 - time2).strftime('%H:%M:%S'))
Assuming you want the time 5 minutes ago, you can use timedelta without any string manipulation:
five_min_ago = datetime.datetime.now() - datetime.timedelta(minutes = 5)
I need to find "yesterday's" date in this format MMDDYY in Python.
So for instance, today's date would be represented like this:
111009
I can easily do this for today but I have trouble doing it automatically for "yesterday".
Use datetime.timedelta()
>>> from datetime import date, timedelta
>>> yesterday = date.today() - timedelta(days=1)
>>> yesterday.strftime('%m%d%y')
'110909'
from datetime import datetime, timedelta
yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%m%d%y')
This should do what you want:
import datetime
yesterday = datetime.datetime.now() - datetime.timedelta(days = 1)
print yesterday.strftime("%m%d%y")
all answers are correct, but I want to mention that time delta accepts negative arguments.
>>> from datetime import date, timedelta
>>> yesterday = date.today() + timedelta(days=-1)
>>> print(yesterday.strftime('%m%d%y')) #for python2 remove parentheses
Could I just make this somewhat more international and format the date according to the international standard and not in the weird month-day-year, that is common in the US?
from datetime import datetime, timedelta
yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%Y-%m-%d')
To expand on the answer given by Chris
if you want to store the date in a variable in a specific format, this is the shortest and most effective way as far as I know
>>> from datetime import date, timedelta
>>> yesterday = (date.today() - timedelta(days=1)).strftime('%m%d%y')
>>> yesterday
'020817'
If you want it as an integer (which can be useful)
>>> yesterday = int((date.today() - timedelta(days=1)).strftime('%m%d%y'))
>>> yesterday
20817
I'm curious about manipulating time in Python. I can get the (last modified) age of a file using the os.path.getmtime() function as such:
import os.path, time
os.path.getmtime(oldLoc)
I need to run some kind of test to see whether this time is within the last three months or not, but I'm thoroughly confused by all the available time options in Python.
Can anyone offer any insight? Kind Regards.
time.time() - os.path.getmtime(oldLoc) > (3 * 30 * 24 * 60 * 60)
You can use a bit of datetime arthimetic here for the sake of clarity.
>>> import datetime
>>> today = datetime.datetime.today()
>>> modified_date = datetime.datetime.fromtimestamp(os.path.getmtime('yourfile'))
>>> duration = today - modified_date
>>> duration.days > 90 # approximation again. there is no direct support for months.
True
To find whether a file is older than 3 calendar months, you could use dateutil.relativedelta:
#!/usr/bin/env python
import os
from datetime import datetime
from dateutil.relativedelta import relativedelta # $ pip install python-dateutil
three_months_ago = datetime.now() - relativedelta(months=3)
file_time = datetime.fromtimestamp(os.path.getmtime(filename))
if file_time < three_months_ago:
print("%s is older than 3 months" % filename)
The exact number of days in "last 3 months" may differ from 90 days in this case. If you need 90 days exactly instead:
from datetime import datetime, timedelta
three_months_ago = datetime.now() - timedelta(days=90)
If you want to take into account the changes in the local utc offset, see Find if 24 hrs have passed between datetimes - Python.
I was looking for something similar and came up with this alternative solution:
from os import path
from datetime import datetime, timedelta
two_days_ago = datetime.now() - timedelta(days=2)
filetime = datetime.fromtimestamp(path.getctime(file))
if filetime < two_days_ago:
print "File is more than two days old"
If you need to have the exact number of days you can use the calendar module in conjunction with datetime, e.g.,
import calendar
import datetime
def total_number_of_days(number_of_months=3):
c = calendar.Calendar()
d = datetime.datetime.now()
total = 0
for offset in range(0, number_of_months):
current_month = d.month - offset
while current_month <= 0:
current_month = 12 + current_month
days_in_month = len( filter(lambda x: x != 0, c.itermonthdays(d.year, current_month)))
total = total + days_in_month
return total
And then feed the result of total_number_of_days() into the code that others have provided for the date arithmetic.
1 day = 24 hours = 86400 seconds. Then 3 months is roughly 90 days which is 90 * 86400 seconds. You can use this information to add/subtract time. Or you can try the Python datetime module for date maths. (especially timedelta )
This is to know whether a date is 3 months older
from datetime import date, timedelta
time_period=date.today()-date(2016, 8, 10) < timedelta(days = 120)
Here is a generic solution using time deltas:
from datetime import datetime
def is_file_older_than (file, delta):
cutoff = datetime.utcnow() - delta
mtime = datetime.utcfromtimestamp(os.path.getmtime(file))
if mtime < cutoff:
return True
return False
To detect a file older than 3 months we can either approximate to 90 days:
from datetime import timedelta
is_file_older_than(filename, timedelta(days=90))
Or, if you are ok installing external dependencies:
from dateutil.relativedelta import relativedelta # pip install python-dateutil
is_file_older_than(filename, relativedelta(months=3))
There has to be an easier way to do this. I have objects that want to be refreshed every so often, so I want to record when they were created, check against the current timestamp, and refresh as necessary.
datetime.datetime has proven to be difficult, and I don't want to dive into the ctime library. Is there anything easier for this sort of thing?
if you want to compute differences between two known dates, use total_seconds like this:
import datetime as dt
a = dt.datetime(2013,12,30,23,59,59)
b = dt.datetime(2013,12,31,23,59,59)
(b-a).total_seconds()
86400.0
#note that seconds doesn't give you what you want:
(b-a).seconds
0
import time
current = time.time()
...job...
end = time.time()
diff = end - current
would that work for you?
>>> from datetime import datetime
>>> a = datetime.now()
# wait a bit
>>> b = datetime.now()
>>> d = b - a # yields a timedelta object
>>> d.seconds
7
(7 will be whatever amount of time you waited a bit above)
I find datetime.datetime to be fairly useful, so if there's a complicated or awkward scenario that you've encountered, please let us know.
EDIT: Thanks to #WoLpH for pointing out that one is not always necessarily looking to refresh so frequently that the datetimes will be close together. By accounting for the days in the delta, you can handle longer timestamp discrepancies:
>>> a = datetime(2010, 12, 5)
>>> b = datetime(2010, 12, 7)
>>> d = b - a
>>> d.seconds
0
>>> d.days
2
>>> d.seconds + d.days * 86400
172800
We have function total_seconds() with Python 2.7
Please see below code for python 2.6
import datetime
import time
def diffdates(d1, d2):
#Date format: %Y-%m-%d %H:%M:%S
return (time.mktime(time.strptime(d2,"%Y-%m-%d %H:%M:%S")) -
time.mktime(time.strptime(d1, "%Y-%m-%d %H:%M:%S")))
d1 = datetime.now()
d2 = datetime.now() + timedelta(days=1)
diff = diffdates(d1, d2)
Here's the one that is working for me.
from datetime import datetime
date_format = "%H:%M:%S"
# You could also pass datetime.time object in this part and convert it to string.
time_start = str('09:00:00')
time_end = str('18:00:00')
# Then get the difference here.
diff = datetime.strptime(time_end, date_format) - datetime.strptime(time_start, date_format)
# Get the time in hours i.e. 9.60, 8.5
result = diff.seconds / 3600;
Hope this helps!
Another approach is to use timestamp values:
end_time.timestamp() - start_time.timestamp()
By reading the source code, I came to a conclusion: the time difference cannot be obtained by .seconds:
#property
def seconds(self):
"""seconds"""
return self._seconds
# in the `__new__`, you can find the `seconds` is modulo by the total number of seconds in a day
def __new__(cls, days=0, seconds=0, microseconds=0,
milliseconds=0, minutes=0, hours=0, weeks=0):
seconds += minutes*60 + hours*3600
# ...
if isinstance(microseconds, float):
microseconds = round(microseconds + usdouble)
seconds, microseconds = divmod(microseconds, 1000000)
# ! 👇
days, seconds = divmod(seconds, 24*3600)
d += days
s += seconds
else:
microseconds = int(microseconds)
seconds, microseconds = divmod(microseconds, 1000000)
# ! 👇
days, seconds = divmod(seconds, 24*3600)
d += days
s += seconds
microseconds = round(microseconds + usdouble)
# ...
total_seconds can get an accurate difference between the two times
def total_seconds(self):
"""Total seconds in the duration."""
return ((self.days * 86400 + self.seconds) * 10**6 +
self.microseconds) / 10**6
in conclusion:
from datetime import datetime
dt1 = datetime.now()
dt2 = datetime.now()
print((dt2 - dt1).total_seconds())
Is there a built-in method for converting a date to a datetime in Python, for example getting the datetime for the midnight of the given date? The opposite conversion is easy: datetime has a .date() method.
Do I really have to manually call datetime(d.year, d.month, d.day)?
You can use datetime.combine(date, time); for the time, you create a datetime.time object initialized to midnight.
from datetime import date
from datetime import datetime
dt = datetime.combine(date.today(), datetime.min.time())
There are several ways, although I do believe the one you mention (and dislike) is the most readable one.
>>> import datetime
>>> t=datetime.date.today()
>>> datetime.datetime.fromordinal(t.toordinal())
datetime.datetime(2009, 12, 20, 0, 0)
>>> datetime.datetime(t.year, t.month, t.day)
datetime.datetime(2009, 12, 20, 0, 0)
>>> datetime.datetime(*t.timetuple()[:-4])
datetime.datetime(2009, 12, 20, 0, 0)
and so forth -- but basically they all hinge on appropriately extracting info from the date object and ploughing it back into the suitable ctor or classfunction for datetime.
The accepted answer is correct, but I would prefer to avoid using datetime.min.time() because it's not obvious to me exactly what it does. If it's obvious to you, then more power to you. I also feel the same way about the timetuple method and the reliance on the ordering.
In my opinion, the most readable, explicit way of doing this without relying on the reader to be very familiar with the datetime module API is:
from datetime import date, datetime
today = date.today()
today_with_time = datetime(
year=today.year,
month=today.month,
day=today.day,
)
That's my take on "explicit is better than implicit."
You can use the date.timetuple() method and unpack operator *.
args = d.timetuple()[:6]
datetime.datetime(*args)
Today being 2016, I think the cleanest solution is provided by pandas Timestamp:
from datetime import date
import pandas as pd
d = date.today()
pd.Timestamp(d)
Timestamp is the pandas equivalent of datetime and is interchangable with it in most cases. Check:
from datetime import datetime
isinstance(pd.Timestamp(d), datetime)
But in case you really want a vanilla datetime, you can still do:
pd.Timestamp(d).to_datetime()
Timestamps are a lot more powerful than datetimes, amongst others when dealing with timezones. Actually, Timestamps are so powerful that it's a pity they are so poorly documented...
you can also use
date = datetime.utcnow().date()
dt = datetime.fromisoformat(date.isoformat())
print(dt)
datetime.datetime(2021, 11, 15, 0, 0)
One way to convert from date to datetime that hasn't been mentioned yet:
from datetime import date, datetime
d = date.today()
datetime.strptime(d.strftime('%Y%m%d'), '%Y%m%d')
You can use easy_date to make it easy:
import date_converter
my_datetime = date_converter.date_to_datetime(my_date)
Do I really have to manually call datetime(d.year, d.month, d.day)
No, you'd rather like to call
date_to_datetime(dt)
which you can implement once in some utils/time.py in your project:
from typing import Optional
from datetime import date, datetime
def date_to_datetime(
dt: date,
hour: Optional[int] = 0,
minute: Optional[int] = 0,
second: Optional[int] = 0) -> datetime:
return datetime(dt.year, dt.month, dt.day, hour, minute, second)
To make dt timezone aware datetime (with Django timezone util):
from django.utils import timezone
timezone.now().replace(*(*dt.timetuple()[:6], 0))
An alternative to toisoformat/fromisoformat: you can use date.toordinal and datetime.fromordinal:
import datetime
start_date = datetime.date(1991, 2, 20)
start_date_midnight = datetime.datetime.fromordinal(start_date.toordinal())
I suspect this is more efficient than converting to/from a string.
You can test this process as so:
def test_datetime_from_date():
for x in range(1,1000000):
date_ = datetime.date.fromordinal(x)
datetime_ = datetime.datetime.fromordinal(date_.toordinal())
datetime_iso_date, t, datetime_iso_time = datetime_.isoformat().partition("T")
assert datetime_iso_date == date_.isoformat()
You can use this class:
import time
import datetime
class TimingClass():
def __init__(self):
self.YEAR = datetime.date.today().year
self.MONTH = datetime.date.today().month
self.DATE = datetime.date.today().day
self.HOUR = datetime.datetime.now().hour
self.MINUTE = datetime.datetime.now().minute
self.SECONDS = datetime.datetime.now().second
self.TODAY = datetime.date.today()
self.YESTERDAY = datetime.datetime.strftime( (self.TODAY - datetime.timedelta(days = 1)) , '%Y-%m-%d')
self.TOMORROW = datetime.datetime.strftime( (self.TODAY + datetime.timedelta(days = 1)) , '%Y-%m-%d')
self.TODAY_datetime = datetime.datetime.combine(datetime.date.today(), datetime.datetime.min.time())
If you need something quick, datetime_object.date() gives you a date of a datetime object.
I am a newbie to Python. But this code worked for me which converts the specified input I provide to datetime. Here's the code. Correct me if I'm wrong.
import sys
from datetime import datetime
from time import mktime, strptime
user_date = '02/15/1989'
if user_date is not None:
user_date = datetime.strptime(user_date,"%m/%d/%Y")
else:
user_date = datetime.now()
print user_date