I have a dataset with the dates given in numbers from 1995 to 2016.
1/1/1995 is equal to 1, 2/1/1995 is 2 and 31/12/2016 is 8036, so every day is one number.
How do I turn my time array [1,2,3,...,8034,8035,8036] into dates of dd/mm/yyyy?
Use the datetime.fromordinal(x) method. This creates a date from the number x, signifying the number of days since 0001-01-01.
If you want to start with x==1 being 1995-01-01, you can do
d = datetime.date(1,1,1) # actual date does not matter
print d.fromordinal( datetime.date(1994,12,31).toordinal() + x)
where x is the number of days since the last day of 1994.
Use the epoch conversion which is also supported by the python time library. The unix epoch time starts on 01/01/1970 and is counted in seconds. If you add 788932800 seconds to reach 01/01/1995, you can then add 86400 (seconds per day) and can use standard techniques to calculated the "seconds from epoch" back to a correct date.
Example code:
#!/usr/bin/python
import time
entryid = 5
epochdate = 788932800 + entryid * 86400
print time.strftime("%d/%m/%y", time.gmtime(epochdate))
does this help for first 100 days? You can change the no though.
import time
epochOne = 788918400 #epoch for 1995-01-01 00:00:00
oneDay = 86400 #epoch for 86400
noOfDays = 8036
for each in range(noOfDays):
epochEach = epochOne + (each * oneDay)
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(epochEach)))
Related
I'm currently trying to fill in some bad data.
Sometimes there is a Start Date and no End Date and sometimes there is an End Date and no Start Date, but the table gives the Duration (in days) of the task and the Work Week Length.
(Note: Work Week Length is 5 day (excludes weekends), 6 day (excludes Sunday), and 7 day.)
Example of the Table
How would I go about this?
I've calculated unknown Durations already with Start/End Dates and Work Week Length, but am unsure how to go about doing things a little backwards.
You can use the timedelta function of the datetime module to help you.
You can calculate the number of days by working out the full weeks (7 per week) + any additional days worked after accounting for the weeks.
Here is an example:
import datetime
# sample data
start_date = "07/01/2022"
duration = 6
work_week = 5
# calculate the days to add (full weeks + left over days)
days = (7 * (duration // work_week)) + (duration % work_week)
# add the days to the start date
end_date = datetime.datetime.strptime(start_date, "%d/%m/%Y") + datetime.timedelta(days=days)
# display the result
print(end_date)
If you have an end date and wish to find the start date then the code is similar to the above except you subtract the number of days from the end date:
# subtract the days from the end date
start_date = datetime.datetime.strptime(end_date, "%d/%m/%Y") - datetime.timedelta(days=days)
You can adapt the above examples to work with your database. It may be useful to create a suitable function that you can call as shown below:
def calculate_date(date, duration, work_week, is_end_date=False):
# calculate the weeks
weeks = (7 * (duration // work_week))
# calculate remaining work days
remaining_days = (duration % work_week)
# calculate total actual days
days = weeks + remaining_days
# determine date
current = datetime.datetime.strptime(start_date, "%d/%m/%Y")
if is_end_date:
result = current - datetime.timedelta(days=days)
else:
result = current + datetime.timedelta(days=days)
return result
I have two date time objects
`statrt_time` and `end_time`
my code is
if self.book_from and self.book_to:
fmt = '%Y-%m-%d %H:%M:%S'
s = datetime.strptime(self.book_from,fmt) #start date
e = datetime.strptime(self.book_to,fmt) #end date
diff = e - s
total_seconds=diff.seconds
time_diff = (total_seconds/3600.0)
no_of_units = (time_diff/4)
if(e<s):
self.units = 0
else:
self.units = math.ceil(no_of_units)
Here when I subtract time within the same day it is giving the correct difference. But when the day is changed, it is not calculating the day difference but only giving time difference. How can I add day difference also?
Use total_seconds() instead of seconds.
timedelta.seconds just shows "second" part of the difference, while total_seconds() shows the duration of the difference in seconds. See Mureinik's answer for more details.
So, use this:
total_seconds=diff.total_seconds()
total_seconds is a timedelta object which stores the difference between two datetimes using three fields - days, seconds and miliseconds. Your snippet just uses the seconds attributes instead of the entire difference. The total_seconds() method takes care of this for you and returns, well, the total number of seconds between two datatimes.
I got another way of doing.. BUT A WORK AROUND..
if self.book_from and self.book_to:
fmt = '%Y-%m-%d %H:%M:%S'
s = datetime.strptime(self.book_from,fmt) #start date
e = datetime.strptime(self.book_to,fmt) #end date
diff = e - s
days=diff.days// convert difference to day instead of seconds//
days_seconds=0
if(days>0): //Checking whether the difference exceeds a day//
days_seconds=days*24*3600 //If so convert it to seconds//
total_seconds=diff.seconds+days_seconds
time_diff = (total_seconds/3600.0)
I want to calculate difference between two time in hours using django in sql db the time are stored in timefield.
I tried this:
def DesigInfo(request): # attendance summary
emplist = models.staff.objects.values('empId', 'name')
fDate = request.POST.get('fromDate')
tDate = request.POST.get('toDate')
if request.GET.get('empId_id'):
sel = attendance.objects.filter(empId_id=request.GET.get('empId_id'),)
for i in sel:
# print i.
# print i.outTime
# print i.inTime.hour,i.inTime.minute,i.inTime.second - i.outTime.hour,i.outTime.minute,i.outTime.second
ss = i.inTime.hour
ss1 = 12 - ss
mm = i.outTime.hour
mm1 = (12 + mm) - 12
print ss1 + mm1
Since i.inTime and i.outTime are time objects you cannot simply subtract them. A good approach is to convert them to datetime adding the date part (use today() but it is irrelevant to the difference), then subtract obtaining a timedelta object.
delta = datetime.combine(date.today(), i.outTime) - datetime.combine(date.today(), i.inTime)
(Look here: subtract two times in python)
Then if you want to express delta in hours:
delta_hours = delta.days * 24 + delta.seconds / 3600.0
A timedelta object has 3 properties representing 3 different resolutions for time differences (days, seconds and microseconds). In the last expression I avoided to add the microseconds but I suppose it is not relevant in your case. If it is also add delta.microseconds / 3600000000.0
Note that simply dividing seconds by 3600 would have returned only the integer part of hours avoiding fractions. It depends on your business rules how to round it up (round, floor, ceil or leave the fractional part as I did)
Using datetime objects: https://docs.python.org/2/library/datetime.html
A good stack overflow post on the topic How to get current time in Python
from datetime import datetime
now = datetime.now()
# wait some time
then = ... some time
# diff is a datetime.timedelta instance
diff = then - now
diff_hours = diff.seconds / 3600
You might want to play with this codes:
from datetime import datetime
#set the date and time format
date_format = "%m-%d-%Y %H:%M:%S"
#convert string to actual date and time
time1 = datetime.strptime('8-01-2008 00:00:00', date_format)
time2 = datetime.strptime('8-02-2008 01:30:00', date_format)
#find the difference between two dates
diff = time2 - time1
''' days and overall hours between two dates '''
print ('Days & Overall hours from the above two dates')
#print days
days = diff.days
print (str(days) + ' day(s)')
#print overall hours
days_to_hours = days * 24
diff_btw_two_times = (diff.seconds) / 3600
overall_hours = days_to_hours + diff_btw_two_times
print (str(overall_hours) + ' hours');
''' now print only the time difference '''
''' between two times (date is ignored) '''
print ('\nTime difference between two times (date is not considered)')
#like days there is no hours in python
#but it has seconds, finding hours from seconds is easy
#just divide it by 3600
hours = (diff.seconds) / 3600
print (str(hours) + ' Hours')
#same for minutes just divide the seconds by 60
minutes = (diff.seconds) / 60
print (str(minutes) + ' Minutes')
#to print seconds, you know already ;)
print (str(diff.seconds) + ' secs')
The easiest way through I achieve is the comment of Zac given above. I was using relativedelta like this
from dateutil import relativedelta
difference = relativedelta.relativedelta( date1, date2)
no_of_hours = difference.hours
but it did not give me correct result when the days changes. So, I used the approach expressed above:
no_of_hours = (difference.days * 24) + (difference.seconds / 3600)
Please note that you will be getting negative value if date2 is greater than date1. So, you need to swipe the position of date variables in relativedelta.
I am trying to create an alarm/schedule based timeclock from a string that I get returned from a Telit HE910 modem. The AT command is AT+CCLK and the string result is: +CCLK: "2015/03/26,14:23:22+40". I have broken the string down into a time stamp of variables containing -
YYYY - year / MM - month / DD - day / hh - hour / mm - minute / ss - seconds / ampm - AM or PM. All variables are strings and numeric types can safely float(mm) etc.
The problem I am having is I'm not sure how to compare the minutes if my program is off doing another part of the program and it misses the exact minute as per the code below. Can anyone enlighten an easier way of doing this so that minutes can be compared plus 5 minutes in case the system is elsewhere especially if the alarm set time is XX hours 59 minutes. (Another part of the system could hold the program from seeing this code for 5 minutes or so)
def alarm_function(Time, Alarm): # Time Dictionary, Alarm Dictionary
if Time['ampm'] == Alarm['ampm']:
if Time['hh'] == Alarm['hh']:
if float(Time['mm']) == ((float(Alarm['mm']) or (float(Alarm['mm'] + 1) or (float(Alarm['mm'] + 2) or (float(Alarm['mm'] + 3) or (float(Alarm['mm'] + 4) or (float(Alarm['mm'] + 5)):
return True
return False
Minute comparison for visual expression only...
Here's how you could parse AT+CCLK? response into a datetime object representing time in UTC:
from datetime import datetime, timedelta
cclk_answer = "+CCLK: 15/03/26,14:23:22+40"
local_time = datetime.strptime(cclk_answer[:-3], "+CCLK: %y/%m/%d,%H:%M:%S")
utc_offset = timedelta(minutes=15*int(cclk_answer[-3:]))
utc_time = local_time - utc_offset
# -> datetime.datetime(2015, 3, 26, 4, 23, 22)
Note: use %Y if the year is 4-digit, though the manual says that the year is represented using 2 digits (%y).
Once you have the utc time, you can compare it directly with other datetime objects (in UTC):
if abs(utc_time - alarm_time) < timedelta(minutes=5):
print("the modem time is within 5 minutes from the alarm time")
btw, to get the current time in UTC, current_time = datetime.utcnow().
I have a function that accepts a date and returns the difference in time between then and the current time (in seconds). It works fine for everything less than a day. But when I even enter a date that's a year in the future, it still returns a number around 84,000 seconds (there are around 86,400 seconds in a day).
def calc_time(date):
future_date = str(date)
t_now = str(datetime.utcnow())
t1 = datetime.strptime(t_now, "%Y-%m-%d %H:%M:%S.%f")
t2 = datetime.strptime(future_date, "%Y-%m-%d %H:%M:%S.%f")
return ((t2-t1).seconds)
Even when I run it with a parameter whose date is in 2014, i get a number way too low.
Anyone have any insight?
Reading the datetime.timedelta docs.
All arguments are optional and default to 0. Arguments may be ints,
longs, or floats, and may be positive or negative.
Only days, seconds and microseconds are stored internally. Arguments
are converted to those units:
A millisecond is converted to 1000 microseconds. A minute is converted
to 60 seconds. An hour is converted to 3600 seconds. A week is
converted to 7 days. and days, seconds and microseconds are then
normalized so that the representation is unique, with
0 <= microseconds < 1000000 0 <= seconds < 3600*24 (the number of
seconds in one day)
-999999999 <= days <= 999999999
The solution is to use .total_seconds() instead of .seconds
The following code will return you the number of days between the two given dates
$daysremaining = ceil(abs(strtotime($yourdate) - strtotime($currentdate)) / 86400);
and to get the difference in seconds use
$secondsremaining = strtotime($yourdate) - strtotime($currentdate);
upvote if useful
ahh. apparently .seconds will only return the difference of seconds within the range of a day.
.seconds will include both hours and minutes, so i needed to add that to .days*86400 to get total seconds.
thanks for the help, everyone! ;D