I am trying to generate a date with range but the time is not showing. The code is as follows:
def date_range(start, end, step: datetime.timedelta):
while start < end:
yield start
start += step
for d in date_range(
start=datetime.date(2019, 1, 1),
end=datetime.date(2019, 1, 15),
step=datetime.timedelta(days=7),
):
print(d)
>>>2019-01-01
>>>2019-01-08
The code shows the date only without the time. Why???
You are using datetime.date() which, according to the Python documentation here does not include time information - it just sets the hours/minutes/seconds to 0.
I think you want to use datetime.datetime() which does include time information.
See the Python documentation on datetime.datetime() for more information.
Related
I'm attempting to build an alarm application but I'm struggling to get the 'schedule' module to function how I'd like it to. The problem is that I can't seem to schedule multiple alarms for one day while calling the day attribute via an array.
Example of how you'd normally schedule multiple times for one day:
schedule.every().sunday.at('17:25').do(job)
schedule.every().sunday.at('17:30').do(job)
schedule.every().sunday.at('17:35').do(job)
This works fine, but I really want to load times with a for loop so I don't have a giant if statement, and so that I can load times dynamically:
dayArray = [
schedule.every().sunday,
schedule.every().monday,
schedule.every().tuesday,
schedule.every().wednesday,
schedule.every().thursday,
schedule.every().friday,
schedule.every().saturday
]
for i in range(1, xlsxAlarmSheet.ncols):
for j in range(1, 8):
if(str(xlsxAlarmSheet.cell_value(j, i)) != '0'):
dayArray[j - 1].at(str(xlsxAlarmSheet.cell_value(j, i))[:2] + ':' + str(xlsxAlarmSheet.cell_value(j, i))[2:]).do(job)
The days are being loaded from an array and the times from an xlsx file via the XLRD module. The only problem is the alarms are overwriting each other somehow when I schedule multiple times for one day. If I schedule 3 times for Sunday with this method for example, only the third scheduled time fires off. I thought it must be because when I load the days into an array they are no longer unique somehow, so I tried doing a 2-dimensional array:
dayArray = [[
schedule.every().sunday,
schedule.every().monday,
schedule.every().tuesday,
schedule.every().wednesday,
schedule.every().thursday,
schedule.every().friday,
schedule.every().saturday
]] * (xlsxAlarmSheet.ncols - 1)
for i in range(1, xlsxAlarmSheet.ncols):
for j in range(1, 8):
if(str(xlsxAlarmSheet.cell_value(j, i)) != '0'):
dayArray[i - 1][j - 1].at(str(xlsxAlarmSheet.cell_value(j, i))[:2] + ':' + str(xlsxAlarmSheet.cell_value(j, i))[2:]).do(job)
With no luck... the times are still overwriting each other, any ideas?
Disclaimer: 0 Python experience, only JavaScript.... But...
Try to not call the function within the array of objects like that:
dayArray = [[
schedule.every().sunday,
...
Instead just have the name of the day (the only part which is varying)
dayArray = [[
'sunday', 'monday', ...
Then in the for each use that string name when you build the function
for each .... { schedule.every()[dayArray[i]].at(...).do(...) }
My random guess is that it's somehow getting called incorrectly when stored that way, just store the part that is different (the day name), since you can just call the rest of that function in the loop (since it's the same for all).
Hopefully that makes sense. No idea if it will work, just something to try. Good luck.
I think you may need to use an index to store your values. This link might help.
https://treyhunner.com/2016/04/how-to-loop-with-indexes-in-python/#What_if_we_need_indexes?
In another question I posted, I was originally trying to substitute the day attribute with a string, like Vig is suggesting with his answer to this post. This wasn't working for me, so I ended up storing objects in an array, as Prune suggested on my original question.
However, Prune also posted a link to an example (example 7) in which the entire call to schedule a time was stored in a string and then called via eval(), which seems to work.
So this is what I ended up doing:
dayArray = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
dayTimeArray = []
for i in range(1, xlsxAlarmSheet.ncols):
for j in range(1, 8):
if(str(xlsxAlarmSheet.cell_value(j, i)) != '0'):
dayTimeArray.append(
"schedule.every().{}.at('{}').do(StartSubProcess)".format(
dayArray[j - 1],
str(xlsxAlarmSheet.cell_value(j, i))[:2] + ':' + str(xlsxAlarmSheet.cell_value(j ,i))[2:]
)
)
for i in range(0, len(dayTimeArray)):
eval(dayTimeArray[i])
I'm doing an application which parse a XML from http request and one of the attributes is a date.
The problem is that the format is a string without separation, for example: '20190327200000000W' and I need to transform it into a datetime format to send it to a database.
All the information I have found is with some kind of separation char (2019-03-23 ...). Can you help me?
Thanks!!!
Maybe this? (in jupypter notebook)
from datetime import datetime
datetime_object = datetime.strptime('20190327200000000W', '%Y%m%d%H%M%S%fW')
datetime_object
Well I have solved this, at first I did that Xenobiologist said, but I had a format problem, so I decided to delete the last character (the X of %X)...and I realized that I hadn't a string, I had a list, so I transformed to string and did the operations. My code (I'll put only the inside for loop part, without the parsing part):
for parse in tree.iter(aaa):
a = parse.get(m)
respon = a.split(' ')
if m == 'Fh':
x = str(respon[0])
x2 = len(x)
x3 = x[:x2-1]
print (x3)
y = time.strptime(x3, "%Y%m%d%H%M%S%f")
I have a Python script that generates .csv files from other data sources.
Currently, an error happens when the user manually adds a space to a date by accident. Instead of inputting the date as "1/13/17", a space may be added at the front (" 1/13/17") so that there's a space in front of the month.
I've included the relevant part of my Python script below:
def processDateStamp(sourceStamp):
matchObj = re.match(r'^(\d+)/(\d+)/(\d+)\s', sourceStamp)
(month, day, year) = (matchObj.group(1), matchObj.group(2), matchObj.group(3))
return "%s/%s/%s" % (month, day, year)
How do I trim the space issue in front of month and possibly on other components of the date (the day and year) as well for the future?
Thanks in advance.
Since you're dealing with dates, it might be more appropriate to use datetime.strptime than regex here. There are two advantages of this approach:
It makes it slightly clearer to anyone reading that you're trying to parse dates.
Your code will be more prone to throw exceptions when trying to parse data that doesn't represent dates, or represent dates in an incorrect format - this is good because it helps you catch and address issues that might otherwise go unnoticed.
Here's the code:
from datetime import datetime
def processDateStamp(sourceStamp):
date = datetime.strptime(sourceStamp.replace(' ', ''), '%M/%d/%y')
return '{}/{}/{}'.format(date.month, date.day, date.year)
if __name__ == '__main__':
print(processDateStamp('1/13/17')) # 1/13/17
print(processDateStamp(' 1/13/17')) # 1/13/17
print(processDateStamp(' 1 /13 /17')) # 1/13/17
You also can use parser from python-dateutil library. The main benefit you will get - it can recognize the datetime format for you (sometimes it may be useful):
from dateutil import parser
from datetime import datetime
def processDateTimeStamp(sourceStamp):
dt = parser.parse(sourceStamp)
return dt.strftime("%m/%d/%y")
processDateTimeStamp(" 1 /13 / 17") # returns 01/13/17
processDateTimeStamp(" jan / 13 / 17")
processDateTimeStamp(" 1 - 13 - 17")
processDateTimeStamp(" 1 .13 .17")
Once again, a perfect opportunity to use split, strip, and join:
def remove_spaces(date_string):
date_list = date_string.split('/')
result = '/'.join(x.strip() for x in date_list)
return result
Examples
In [7]: remove_spaces('1/13/17')
Out[7]: '1/13/17'
In [8]: remove_spaces(' 1/13/17')
Out[8]: '1/13/17'
In [9]: remove_spaces(' 1/ 13/17')
Out[9]: '1/13/17'
I'm trying to do a search between two dates with sqlalchemy. If I used static dates will be this way.
def secondExercise():
for instance in session.query(Puppy.name, Puppy.weight, Puppy.dateOfBirth).\
filter(Puppy.dateOfBirth <= '2015-08-31', Puppy.dateOfBirth >= '2015-02-25' ).order_by(desc("dateOfBirth")):
print instance
Manipulating dates in python is quite easy.
today = date.today().strftime("%Y/%m/%d")
sixthmonth = date(date.today().year, date.today().month-6,date.today().day).strftime("%Y/%m/%d")
The problem is, I don't know how to implement this as parameter. Any help with this?
for instance in session.query(Puppy.name, Puppy.weight, Puppy.dateOfBirth).\
filter(Puppy.dateOfBirth <= today, Puppy.dateOfBirth >= sixthmonth ).order_by(desc("dateOfBirth")):
SQLAlchemy supports comparison by datetime.date() and datetime.datetime() objects.
http://docs.sqlalchemy.org/en/rel_1_0/core/type_basics.html?highlight=datetime#sqlalchemy.types.DateTime
You can expose these as parameters (replace your_query with all the stuff you want to be constant and not parametrized):
six_months_ago = datetime.datetime.today() - datetime.timedelta(180)
today = datetime.datetime.today()
def query_puppies(birth_date=six_months_ago):
for puppy in your_query.filter(Puppy.dateOfBirth.between(birthdate, today)):
print puppy.name # for example..
Also note the usage of the between clause for some extra awesomeness :)
but two seperate clasuses using <= and >= would also work.
cheers
I'm writing a simple script which has a few lines like this:
if (datetime.datetime.hour == 12):
What is the easiest way to test these? Changing the system time to different times every time I want to test it is a bit annoying, is there an easier way to let Python think it's a different time?
Create a datetime object now and use it:
import datetime, pytz
testing = False # set to True/False
if testing:
now = datetime.datetime(2011, 1, 1, 12, 23, 34, tzinfo=pytz.utc)
# testing with any time
else:
now = datetime.datetime.now(pytz.utc)
# normal usage with current time
if (now.hour == 12):
...
EDIT: You can also start your script with an optional parameter (check optparse): if it is filled in a YYYYMMDDHHMMSS form, you can parse it:
if optDate:
now = datetime.datetime.strptime(optDate, '%Y%m%d%H%M%S').replace(tzinfo=pytz.utc)
else:
now = datetime.datetime.now(pytz.utc)
Apply your own timezone here if you want.