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))
Related
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')
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I need a function returning a boolean indicating if midnight has just passed.
I came up with this but I am not happy with the "form". Can anyone think of anything better? as in terms of efficiency/elegance?
from datetime import datetime, timedelta
def passed_midnight(delta=1):
time_now = datetime.today # see other comment below
time_ago = time_now() - timedelta(minutes=delta)
# next line with a dummy delta (zero) cuz "datetime.today - timedelta(days=1)" gives an error
today = time_now() - timedelta(days=0)
return today.strftime("%Y%m%d") != time_ago.strftime("%Y%m%d")
>>> print(passed_midnight, 10)
datetime.today - timedelta(days=1) gives an error because datetime.today is a function that needs to be called. This is why you must have felt the need to write time_now() with parentheses: it's calling the function, twice (with different results, because time has a tendency to pass).
Avoid strftime in favour of date(), which returns the date part only (as a datetime.date object).
Use datetime.now() instead of datetime.today() so that subtracting a timedelta can take the timezone (and hence daylight savings time changeovers) into account.
So then you get this:
from datetime import datetime, timedelta
def passed_midnight(delta=1):
time_now = datetime.now()
time_ago = time_now - timedelta(minutes=delta)
return time_now.date() != time_ago.date()
You probably misunderstood how to declare a function and how to call it.
Here is a version that fixed the issues with function calls:
from datetime import datetime, timedelta
def passed_midnight(delta=1):
today = datetime.today()
time_ago = today - timedelta(minutes=delta)
return today.strftime("%Y%m%d") != time_ago.strftime("%Y%m%d")
>>> print(passed_midnight(10))
False
Be careful, this code doesn't take care of time zones. The behavior will be different from a location to another
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!")
import datetime
now = datetime.datetime.now()
if now.day == Tuesday :
print ('yes it is tuesday')
else :
print ('no')
I try this but I get error in python :
Traceback (most recent call last):
File "C:/Users/Yarlagadda/Desktop/test2.py", line 4, in <module>
if now.day == Tuesday :
NameError: name 'Tuesday' is not defined
>>>
I would like to know mistake
You have two problems with your code.
The first is that the error code is telling you that Tuesday doesn't exist as a variable because you are not making it a string. So change it to 'Tuesday' with the ' around it.
Second is that now.day is going to return a number and not a string day.
Edit: Thanks to #Tomerikoo for pointing out that this returns the day of the month and not the day of the week. Change this to now.weekday() to get the day of the week.
To fix this, you can either compare the number 1 in the if statement instead of the word Tuesday or you can map the numbers to the words. Mapping the numbers to the words is the preferred method since it is easier to maintain and less messy.
Note: The days of the week in now.weekday() will be numbered 0-6 with 0 being Monday and 6 being Sunday.
I'm using a tuple here, but you could use a list, or if you really feel inclined, a dictionary. But a dict is overkill and a list comes with memory overhead that's not needed.
Mapping:
week_days = ("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")
Final Code
import datetime
week_days = ("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")
now = datetime.datetime.now()
day = week_days[now.weekday()] # Note the change to now.weekday()
if day == 'Tuesday' :
print ('yes it is tuesday')
else :
print ('no')
The error is just in if condition that the Tuesday is not used as string. Replace Tuesday by 'Tuesday' and your code is working fine.
For enhancement you may also use list or tuple to keep the weekdays.
import datetime
now = datetime.datetime.now()
if now.day == 'Tuesday':
print ('yes it is tuesday')
else:
print ('no')
this is my firt question here. Thanks in advance.
I have automatically uploaded hundreds of images to a Webfaction server with an incorrect timestamp in the filename and now I have to rename them.
Here is an example:
tl0036_20161121-120558.jpg
myCode_yyyymmdd_hhmmss.jpg
I have to change the "hh" characters 1 hour back, so 12 should be 11. They are the 17th and 18th position. I imagine two ways of doing it:
Math operation: Images are taken from 1am to 11pm, so I see no problem in doing just a math operation like 12-1=11 for all of them.
Conditional: if 17th and 18th characters value are 12, then rename to 11. 24 conditions should be written, from 01 to 23 starting value.
I have found many answers here to replace/rename a fixed string and others about conditional operation, but nothing about my kind of mixed replacement.
Please I need advidce in how the script should be assuming it will be executed into the files folder. I am a novice used to work with bash or python.
Thank you!
Solution using datetime in Python
import time
import datetime
def change_filename(fn):
# EXTRACT JUST THE TIMESTAMP AS A STRING
timestamp_str = fn[7:22]
# CONVERT TO UNIX TIMESTAMP
timestamp = time.mktime(datetime.datetime.strptime(timestamp_str, "%Y%m%d-%H%M%S").timetuple())
# SUBTRACT AN HOUR (3600 SECONDS)
timestamp = timestamp - 3600
# CHANGE BACK TO A STRING
timestamp_str = datetime.datetime.fromtimestamp(timestamp).strftime("%Y%m%d-%H%M%S")
# RETURN THE FILENAME WITH THE NEW TIMESTAMP
return fn[:7] + timestamp_str + fn[22:]
This takes into account possible changes in the day, month, and year that could happen by putting the timestamp back an hour. If you're using a 12-hour time rather than 24 hour, you can use the format string "%Y%m%d-%I%M%S" instead; see the Python docs.
Credit to: Convert string date to timestamp in Python and Converting unix timestamp string to readable date in Python
This assumes that your myCode is of a fixed length, if not you could use the str.split method to pull out the hours from after the -, or if your filenames have an unknown number/placement of -s, you could look at using regular expressions to find the hours and replace them using capturing groups.
In Python, you can use a combination of glob and shutil.move to walk through your files and rename them using that function. You might want to use a regular expression to ensure that you only operate on files matching your naming scheme, if there are other files also in the directory/ies.
Naive Solution
With the caveats about the length of myCode and filename format as above.
If your timestamps are using the 24 hour format (00-23 hours), then you can replace the hours by subtracting one, as you say; but you'd have to use conditionals to ensure that you take care of turning 23 into 00, and take care of adding a leading zero to hours less than 10.
An example in Python would be:
def change_filename(fn):
hh = int(fn[16:18])
if hh == 0:
hh = 23
else:
hh -= 1
hh = str(hh)
# ADD LEADING ZERO IF hh < 10
if len(hh) == 1:
hh = '0' + hh
return fn[:16] + str(hh) + fn[18:]
As pointed out above, an important point to bear in mind is that this approach would not put the day back by one if the hour is 00 and is changed to 23, so you would have to take that into account as well. The same could happen for the month, and the year, and you'd have to take these all into account. It's much better to use datetime.
For your file renaming logic, not only are you going to have issues over day boundaries, but also month, year, and leap-year boundaries. For example, if your filename is tl0036_20160101-000558.jpg, it needs to change to tl0036_20151231-230558.jpg. Another example: tl0036_20160301-000558.jpg will be tl0036_20160229-230558.jpg.
Creating this logic from scratch will be very time consuming - but luckily there's the datetime module in Python that has all this logic already built in.
Your script should consist of the following steps:
Iterate through each '.jpg' file in your folder.
Try to match your timestamp file name for each '.jpg'
Extract the timestamp values and create a datetime.datetime object out of those values.
Subtract a datetime.timedelta object equal to 1 hour from that datetime.datetime object, and set that as your new timestamp.
Contstruct a new filename with your new timestamp.
Replace the old filename with the new filename.
Here's an example implementation:
import datetime
import glob
import os
import re
def change_timestamps(source_folder, hourdiff = -1):
file_re = re.compile(r'(.*)_(\d{8}-\d{6})\.jpg')
for source_file_name in glob.iglob(os.path.join(source_folder, '*.jpg')):
file_match = file_re.match(source_file_name)
if file_match is not None:
old_time = datetime.datetime.strptime(file_match.group(2), "%Y%m%d-%H%M%S")
new_time = old_time + datetime.timedelta(hours = hourdiff)
new_file_str = '{}_{}.jpg'.format(file_match.group(1), new_time.strftime("%Y%m%d-%H%M%S"))
new_file_name = os.path.join(source_folder, new_file_str)
os.replace(source_file_name, new_file_name)