I am trying to output an altered time based on the "time" module in Py. For instance. I gather raw_input for the script from a user and based on that input I want to get system time and subtract a number of days from it and use that time for another step.
Thanks,
There are examples of all these steps here.
The datetime module is likely what you want.
Here is an example:
>>> from datetime import datetime, timedelta
>>> s = raw_input('Input year month day hour minute second: ')
Input year month day hour minute second: 2011 10 31 14 30 00
'2011 10 31 14 30 00'
>>> fields = map(int, s.split())
>>> fields
[2011, 10, 31, 14, 30, 0]
>>> userdate = datetime(*[2011, 10, 31, 14, 30, 0])
>>> userdate
datetime.datetime(2011, 10, 31, 14, 30)
>>> userdate - timedelta(days=20)
datetime.datetime(2011, 10, 11, 14, 30)
>>> now = datetime.now()
>>> now
datetime.datetime(2011, 10, 31, 11, 38, 34, 856511)
>>> now + timedelta(hours=2)
datetime.datetime(2011, 10, 31, 13, 38, 34, 856511)
Related
I want total number of hours between mention dates excluding weekend(Saturday, Sunday).
```
start_time = datetime.datetime(2021, 7, 1, 22, 45, 25)
end_time = datetime.datetime(2021, 7, 15, 10, 00, 00)
```
from BusinessHours import BusinessHours
import datetime
start_time = datetime.datetime(2021, 7, 1, 22, 45, 25)
end_time = datetime.datetime(2021, 7, 15, 10, 00, 00)
hours = BusinessHours(start_time, end_time, worktiming=[9, 18], weekends=[6, 7], holidayfile=None)
print(hours.gethours())
This could help you, for more information please refer BusinessHours module in python!
An additional library is needed for my answer (NumPy)
Key elements:
numpy.busday_count to count the number of weekdays
datetime.timedelta(1) to omit starting day (to be checked through if-else to count for minutes)
isoweekday() returns value between 1 and 7, 1 being Monday and 7 Sunday
Steps:
Skip the starting and ending days and find valid in-between days. Multiply by 24 (total hours per day)
Check if starting day is a weekday and calculate the total hours remaining to end that date
Check if the ending day is a weekday and calculate the total hours passed in that day
import datetime
import numpy as np
start_time = datetime.datetime(2021, 7, 1, 22, 45, 25)
end_time = datetime.datetime(2021, 7, 15, 10, 00, 00)
#Step 1.
total_hours=np.busday_count(start_time.date()+datetime.timedelta(1),end_time.date())*24 #already not counting last date
#Step2.
if start_time.isoweekday() in range(1, 6):
total_hours=total_hours+24-start_time.hour-start_time.minute/60-start_time.second/3600
#Step 3.
if end_time.isoweekday() in range(1, 6):
total_hours=total_hours+end_time.hour+end_time.minute/60+end_time.second/3600
print(total_hours)
output: 227.24305555555554
This will do it:
busdays = np.busday_count(start_time.date(), end_time.date())
Assume this is my date time stamp list:
[datetime.datetime(2017, 11, 17, 9, 33, 11), datetime.datetime(2017, 11, 17, 9, 33, 36), datetime.datetime(2017, 11, 17, 9, 33, 48)]
A lot of examples have been given for converting these values to epoch, but the values are in GMT.
How do we convert it to Epoch Local time?
To put it in simpler words. The general epoch conversion coverts the given date into epoch considering that the datetime given is in GMT. But the given date time is localtime!
>>> x = datetime.datetime(2017, 11, 17, 9, 33, 36)
>>> x.timestamp()
1510882416.0
>>> x.ctime()
'Fri Nov 17 09:33:36 2017'
You can use this:
l = [datetime.datetime(2017, 11, 17, 9, 33, 11), datetime.datetime(2017, 11, 17, 9, 33, 36), datetime.datetime(2017, 11, 17, 9, 33, 48)]
epo = [x.strftime('%s') for x in l]
print(epo)
# ['1510898591', '1510898616', '1510898628']
You can try arrow lib:
import arrow
import datetime
x = datetime.datetime(2017, 11, 17, 9, 33, 36)
time = arrow.get(x, 'local').shift(hours=-6) // here you can change hours to what you want
print time
>>2017-11-17T03:33:36+00:00
time = time.format('YYYY-MM-DD HH:mm:ss')
print time
>>2017-11-17 03:33:36
I have a date string like - 2015-01-05T10:30:47-0800,
It looks to me that this is some timezone because of the offset. How can I get a date string which is in the UTC timezone from the above date string.
I tried the following -
datestring = '2015-01-05T10:30:47-0800'
from dateutil import parser
d = parser.parse(datestring) # datetime.datetime(2015, 1, 5, 10, 30, 47, tzinfo=tzoffset(None, -28800))
import pytz
d.astimezone(pytz.timezone('UTC')) # datetime.datetime(2015, 1, 5, 18, 30, 47, tzinfo=<UTC>)
EDIT -
The above code returns the correct answer. My bad!
Try this:
>>> import dateutil.parser
>>> d = dateutil.parser.parse('2015-01-05T10:30:47-0800')
>>> d.astimezone(dateutil.tz.tzutc())
datetime.datetime(2015, 1, 5, 18, 30, 47, tzinfo=tzutc())
How can I generate recurring dates using Python? For example I want to generate recurring date for "Third Friday of every second month". I want to generate recurring dates for daily, weekly, monthly, yearly (i.e., same as the recurrence function in Outlook Express).
import dateutil.rrule as dr
import dateutil.parser as dp
import dateutil.relativedelta as drel
start=dp.parse("19/02/2010") # Third Friday in Feb 2010
This generates the third Friday of every month
rr = dr.rrule(dr.MONTHLY,byweekday=drel.FR(3),dtstart=start, count=10)
This prints every third Friday:
print map(str,rr)
# ['2010-02-19 00:00:00', '2010-03-19 00:00:00', '2010-04-16 00:00:00', '2010-05-21 00:00:00', '2010-06-18 00:00:00', '2010-07-16 00:00:00', '2010-08-20 00:00:00', '2010-09-17 00:00:00', '2010-10-15 00:00:00', '2010-11-19 00:00:00']
rr is an iterable, so you can use slicing notation to pick out every other item. This prints the third Friday of every other month:
print map(str,rr[::2])
# ['2010-02-19 00:00:00', '2010-04-16 00:00:00', '2010-06-18 00:00:00', '2010-08-20 00:00:00', '2010-10-15 00:00:00']
Above, I used str to prettify the output a little bit. For more flexible string formatting of dates, use strftime: See http://au2.php.net/strftime or the man page for strftime for all the options.
print [d.strftime('%d/%m/%Y') for d in rr[::2]]
# ['19/02/2010', '16/04/2010', '18/06/2010', '20/08/2010', '15/10/2010']
You can give dateutil a try - especially its relativedelta and rrule fetures.
you may try to write this yourself. you will first need an iterator which generates dates separated by a given interval:
import datetime
def dateiter(start, resolution):
date = start
while True:
yield date
date += resolution
now, you can generate dates and filter them:
# generate a list of every tuesday of february
# this iterates over every day from now, and filtered according to the rules
# warning: infinite generator below, there is nothing to end the iteration
tuesdays_of_february = (date for date in dateiter(datetime.datetime.now(), datetime.timedelta(days=1)) if date.weekday() == 4 and date.month == 2)
you can call the iterator yourself until you have enough dates:
>>> next(tuesdays_of_february)
datetime.datetime(2010, 2, 19, 14, 25, 46, 171000)
now, you need to limit the results:
>>> from itertools import *
>>>
>>> # get the five next valid dates:
>>> list(islice(tuesdays_of_february),5)
[datetime.datetime(2010, 2,26, 14, 25, 46, 171000), datetime.datetime(2011, 2, 4
, 14, 25, 46, 171000), datetime.datetime(2011, 2, 11, 14, 25, 46, 171000), datet
ime.datetime(2011, 2, 18, 1 4, 25, 46, 171000), datetime.datetime(2011, 2, 25
, 14, 25, 46, 171000)]
>>>
>>> # or until a condition is met:
>>> list(takewhile( lambda date: date.year < 2014, tuesdays_of_february ))
[datetime.datetime(2012, 2, 3, 14, 25, 46, 171000), datetime.datetime(2012, 2, 1
0, 14, 25, 46, 171000), datetime.datetime(2012, 2, 17, 14, 25, 46, 171000), date
time.datetime(2012, 2, 24, 14, 25, 46, 171000), datetime.datetime(2013, 2, 1, 14
, 25, 46, 171000), datetime.datetime(2013, 2, 8, 14, 25, 46, 171000), datetime.d
atetime(2013, 2, 15, 14, 25, 46, 171000), datetime.datetime(2013, 2, 22, 14, 25,
46, 171000)]
don't forget to have a look at the documentation for the datetime module.
Consider:
now = datetime.datetime.now()
now
datetime.datetime(2009, 11, 6, 16, 6, 42, 812098)
How would I create a new datetime object (past) and minus n values from the hours?
Use timedelta in the datetime module:
import datetime
now = datetime.datetime.now()
past = now - datetime.timedelta(hours=10)
Use a timedelta object.
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2009, 11, 6, 16, 35, 50, 593000)
>>> ten_hours = datetime.timedelta(hours=10)
>>> now + ten_hours
datetime.datetime(2009, 11, 7, 2, 35, 50, 593000)
>>> now - ten_hours
datetime.datetime(2009, 11, 6, 6, 35, 50, 593000)
Use a timedelta object.
from datetime import datetime
back = datetime.now() - timedelta(hours=10)