Timedata convertion unsuccessfull [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 12 months ago.
Improve this question
I am trying to create a Python Bot that takes a qr code from my email and sends it to me via Telegram when i want to.
I was able to convert the email data in a list, in this way i am also able to access the date written in the email.
for context the email looks like this:
Gentile STEFANO ZIZZI,
La tua prenotazione per l'evento ANALISI MATEMATICA 1 in data
01/03/2022 09:00 è stata confermata.
L'aula in cui potrai seguire l'evento è: Aula Von Neumann.
Stampa e porta con te il seguente codice a barre:
20220222090620-ffc5d11f-760c-4449-975f-*********
So i have this multidimentional list where the elements are:
0 - the qr code
1 - the place
2 - the subject
3 - the date
and looks like this:
[['20220222090620-ffc5d11f-760c-4449-975f-********'], ['Aula Von
Neumann.'], ['ANALISI MATEMATICA 1 '], ['01/03/2022 09:00']]
Why by running this code, it does not convert the date to datetime succeffuly?
data =''.join(lista[0][3])
if data:
date_time_obj = datetime.strptime(data,'%d/%m/%y %H:%M')
print ("The date is", date_time_obj)
Sorry if there's not the full code but it's honestly too long to copy here, and i think i've given most of the information anyways.
Error:
ValueError: time data '01/03/2022 09:00' does not match format
'%d/%m/%y %H:%M'

To match the date 2022 you must use the %Y, as %y refers to year displayed with 2 digits.
date_time_obj = datetime.strptime(data,'%d/%m/%Y %H:%M')

Related

Why do I have to use a global for imported variable? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 months ago.
Improve this question
import datetime
from datetime import date
def get_one_week():
global date
seven_dates = []
date = date.today()
for i in range(7):
date += datetime.timedelta(days=-1)
date_str = date.strftime('%Y%m%d')
seven_dates.append(date_str)
return seven_dates
print(get_one_week())
This will print out:
['20220901', '20220831', '20220830', '20220829', '20220828', '20220827', '20220826']
My question, both 'date' and 'datetime' are imported variables, but why do I have use a global declaration for the 'date' but not for the 'datetime' variable?
It's because you declared your variable date so python thinks that you referenced the local variable before any assignment try change it to other name so it will use the global one
import datetime
from datetime import date
def get_one_week():
seven_dates = []
d = date.today()
for i in range(7):
d += datetime.timedelta(days=-1)
date_str = d.strftime('%Y%m%d')
seven_dates.append(date_str)
return seven_dates
print(get_one_week())

How to print message if a date condition is met? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
What would a piece of code look like which checks today's date, and if it's a particular date, it will print out a message?
The context is that I'm making a birthday cake for my son who codes and I want to write a themed Happy Birthday message on top correctly. (Sorry, not as clever or serious as a lot of the things on here!)
I'd like something which is basically:
johnsBirthday = 01/01/1998
johnsAge = todaysdate - johnsBirthday (in years)
if todays date == 01/01/XXXX then print("Happy Birthday John!" + johnsAge + " today!")
My knowledge of python is very limited (as I'm sure you can tell from the above) but I vaguely know how to do this in Excel, so I figure there must be a way to do it in python too?
I know could always just write out:
print("Happy Birthday, John!")
and he'd appreciate that, but I think it would really make him smile to go a little further than that!
# Import datetime class from datetime module
from datetime import datetime
birthday = "20/09/1998"
# Parses the string into a datetime object
birthday_obj = datetime.strptime(birthday, '%d/%m/%Y')
# Gets todays date
now = datetime.now()
# Checks the day and month to verify birthday status
if(birthday_obj.day == now.day and birthday_obj.month == now.month):
johns_age = str(now.year - birthday_obj.year)
print("Happy Birthday John! " + johns_age + " today!")
For your purpose, it might be easier to use regular expressions if you are familiar with them. You can search any patterns you like, after converting datetimes to string, or better yet if you already have datetimes in string formats.
For datetime to string format conversion codes, check out -
format-codes
Example code
import re
from datetime import datetime
pattern = re.compile(r'^01/01/')
today_date = datetime.now().strftime(r'%d/%m/%Y')
some_date = '01/01/2021'
print(re.match(pattern, some_date)) # <re.Match object; span=(0, 6), match='01/01/'>
print(today_date) # 20/09/2020
print(pattern.match(today_date)) # None
Edit - Had forgotten that age needs to be calculated!
import re
from datetime import datetime
johns_birthday = '01/01/1998'
if (re.match('^01/01/', johns_birthday)):
johns_age = datetime.now().year - datetime.strptime(johns_birthday, r'%d/%m/%Y').year
print("Happy Birthday John! " + str(johns_age) + " today!")

capture/parsing entries by date range [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
It is possible to capture/parsing entries with 3 days old from current date using standard module "re"?
Below sample file from where I want capture entries.
xx: xxxxxx ; xxxx: 2017-09-2T14:13:17 ; xxxxxxxx: xxxxxxxxxxxxxxxxxxxxxxxxxx
You have to extract with the re module the string with the hour and then:
from datetime import datetime
capturedEntries = []
THREE_DAYS = datetime.timedelta(3)
# I suppose you'are reading lines in another way, but as an example...
for entry in entries:
# I'm assuming each entry follows the format
# xx: xxxxxx ; xxxx: 2017-09-2T14:13:17 ; xxxxxxxx: xxxxxxxxxxxxxxxxxxxxxxxxxx
stringDate = re.search(r'\d{4}-\d{1,2}-\d{1,2}T\d{2}:\d{2}:\d{2}', line)
if stringDate.group():
parsedDate = datetime.strptime(stringDate.group(), '%Y-%m-%dT%H:%M:%S')
timeFromDate = (datetime.today() - parsedDate)
if timeFromDate > THREE_DAYS:
# We save only the datetimes you asked for in datetime format
# For string format, replace parsedDate for stringDate
capturedEntries.append(parsedDate)

can't compare datetime.datetime to builtin_function_or_method [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am new in Django.
I created Sponsor model that model has start_date (start date become sponsor) and end_date (end date of sponsor).
start_date = models.DateField(
_("Start date"),
default=datetime.date.today)
end_date = models.DateField(
_("End date"),
default=datetime.date.today)
I want to put all logic inside the model, if that not possible then I want to put the logic in a view. I make method current_sponsor which can return True or False (if today is on a range of start_date and end_date means True else False).
This is my current_sponsor method
def current_sponsor(self):
today = datetime.date.today
if today >= self.start_date:
return True
elif today <= self.end_date:
return True
else:
return False
The problem is I got error can't compare datetime.datetime to builtin_function_or_method.
I've tried to see the data using django shell it seem works but the reality does not work.
datetime.date.today is not calling the function you think it is:
>>> import datetime
>>> datetime.date.today
<built-in method today of type object at 0x7fb681a90f80> # NOT CALLING FUNCTION
>>> datetime.date.today() # You need () at the end
datetime.date(2015, 11, 4)
If you add the parentheses, you'll get the result you expect.

python regex, date format [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I need a regex for date format in python
I want "March 29"
but not "March 29" in "March 29, YYYY", where YYYY is not 2012
Thanks,
Cheng
You don't need to use regexp.
import datetime
dt = datetime.datetime.now()
print dt.strftime('%B %d')
The result will be:
June 18
BTW, if you want to sort the list of dates and to show year only of those, which are the 2012's, than try to use split():
line = "March 29, YYYY"
if int(line.split(',')[1]) = 2012
print line
else
pass
Sounds like this:
re.compile(r'''^
(january|february|march|...etc.)
\s
\d{1,2}
\s
(,\s2012)?
$''', re.I)
Your question is not 100% clear, but it looks like you're trying to parse a date from an incoming string. If so, use the datetime module rather than a regex. It is more likely to handle locales etc. The datetime.datetime.strptime() method is designed to read dates from strings, so try something like the following:
import datetime
def myDate(raw):
# Try to match a date with a year.
try:
dt = datetime.datetime.strptime(raw, '%B %d, %Y')
# Make sure its the year we want.
if dt.year != 2012:
return None
# Error, try to match without a year.
except ValueError:
try:
dt = datetime.datetime.strptime(raw, '%B %d')
except ValueError:
return None
# Add in the year information - by default it says 1900 since
# there was no year details in the string.
dt = dt.replace(year=2012)
# Strip away the time information and return just the date information.
return dt.date()
The strptime() method returns a datetime object i.e., date and time information. Hence the last line calls the date() method to return just the date. Also note that the function returns None when there is no valid input - you can easily change this to do whatever you situation requires. See the documentation of the strptime() method for details of what the different format codes.
A few examples of its use:
>>> myDate('March 29, 2012')
datetime.date(2012, 3, 29)
>>> myDate('March 29, 2011')
>>> myDate('March 29, 2011') is None
True
>>> myDate('March 29')
datetime.date(2012, 3, 29)
>>> myDate('March 39')
>>> myDate('March 39') is None
True
You'll notice this catches and refuses to accept illegal dates (e.g., March 39) which can be tricky to handle with a regex.
The raw regex to get the month and day is: (january|february|...) \d\d?(?!\s*,\s*\d{4}).
(?!\s*,\s*\d{4}) looks ahead and makes sure the string is not followed by , YYYY. I hope I understood this part of your question. It will not match march 29, 2012 because march 29 is followed by comma space year.
I figured it out by myself
(?!\s*,\s*(1\d\d\d|200\d|2010|2011))

Categories

Resources