I am writing to write something where there are two variables that are formatted in datetime format. The way the user may input their date and time may have the letter "Z" at the end of it. For example:
"2008-01-01T00:00:01Z"
The user may or may not enter in the "Z" at the end so I want to do something that makes either format acceptable. Here's what I have:
import datetime
b = datetime.datetime.strptime("2008-01-01T00:00:01Z", "%Y-%m-%dT%H:%M:%S")
c = datetime.datetime.strptime("2008-05-01T23:59:00Z", "%Y-%m-%dT%H:%M:%S")
def startTime(b):
try:
datetime.datetime.strptime(b, "%Y-%m-%dT%H:%M:%S")
except:
print "Error: start time is invalid."
def endTime(c):
try:
datetime.datetime.strptime(c, "%Y-%m-%dT%H:%M:%S")
except:
print "Error: end time is invalid."
How about just manually removing the Z if it is there?
user_in = raw_input("Please enter a date")
if user_in.endswith('Z'): user_in = user_in[:-1]
rstrip can remove the Z for you if it exists, and leave the string alone otherwise:
>>> "2008-05-01T23:59:00Z".rstrip("Z")
'2008-05-01T23:59:00'
>>> "2008-05-01T23:59:00".rstrip("Z")
'2008-05-01T23:59:00'
So if you have a date s in string format,
date = datetime.datetime.strptime(s.rstrip("Z"), "%Y-%m-%dT%H:%M:%S")
will handle both cases.
Related
our teacher gave us this assignment to make a "password" (not a login, basically make a variable that is always equal to the date and then "if- else" it so the variable is equal to the date )
the code u see is all I tried, I couldn't find anything on the web.
import datetime
x = datetime.datetime.now()
xd=x.strftime("%d")
xm=x.strftime("%m")
xy=x.strftime("%Y")
Date = [xd,xm,xy]
password=input("what is the password?")
if password==Date:
print("well done")
else:
print("try again")
I have no syntax errors
You're going at it in too "divided" of an approach. You can translate the date into a string all at once:
import datetime
x = datetime.datetime.now()
date = x.strftime("%d%m%Y") # will produce '05212019'
# alternatively: "%d,%m,%Y" would produce '05,21,2019' - you can customize this format
password = input("Enter the password. ")
if password == date:
print("Well done")
else:
print("Try again")
First Date is a reserved word so I recommend using date.
date is a list and password is a string so you need to change Date to string
date = ''.join(date) # 21052019
OR
change password to list (assuming input like 21 05 2019)
password = input("what is the password?").split(' ') # ['21', '05', '2019']
OR
don't create a list and just generate the password/date with datetime
date = x.strftime("%d%m%Y") # 21052016
Not sure which format you're after but you could do something like this and then modify the format so that it looks exactly as you need it:
>>> import datetime
>>> datetime.date.today().strftime("%B %d, %Y")
'May 21, 2019'
You could change to ...
*.strftime("%B%d%Y")
... for example if you needed it to remove spaces and commas.
This site https://www.programiz.com/python-programming/datetime/strftime has a very good format code list (%h, %d, %y, etc...) in case you're needing your time bits in different formats.
Right now, Date is a list and password is a string. You'll need to change one to match the other, or they'll never compare equal.
import datetime
x = datetime.datetime.now()
xd=x.strftime("%d")
xm=x.strftime("%m")
xy=x.strftime("%Y")
Date = xd+","+xm+","+xy
password=input("what is the password?")
if password==Date:
print("well done")
else:
print("try again")
I am trying to check if today's date < date downloaded from text file online. Here is my code :
import datetime
import requests
URL = "http://directlinktotextfile.com/text.txt"
result = requests.get(URL)
today = datetime.datetime.now().date()
Url_date = result.text
Url_date.strip()
Url_date = datetime.date(Url_date)
if today < Url_date :
print "Today is less than future date"
raw_input()
else:
print "Today is greater than or = to future date"
raw_input()
The result that comes back is just this : 2018,02,14. I use .strip() in case there might be blank spaces or extra lines. I've printed out result.text after strip() and it shows the correct details. Why is it that I can't check if today < Url_date. It works fine if I enter manually a date into datetime.date(2018,02,14), but when I'm downloading the string it won't work. Any suggestions?
You pass string to datetime.date() which should be each an integer.
Url_list = []
Url_list = Url_date.split(",")
yr = int(Url_list[0])
mn = int(Url_list[1])
d = int(Url_list[2])
Now pass these integers to datetime.date
Url_date = datetime.date(yr, mn, d)
The arguments you pass to datetime.date(arg1, arg2, arg3) are not strings as a whole. When you pass it from url, what you are actually doing is
datetime.date("2018,2,14")
Note that you are passing only one string argument and not 3 different integers. You should split the date string using comma and then convert each into integers and then pass them as arguments to datetime.date.
Here is what your code is trying to do :
Url_date = datetime.date("2018,02,14")
But he wants to have:
Url_date = datetime.date(2018,02,14)
Do
Url_date.split(',') # Result: ['2018','02','14']
And then convert all the string in the array in integers
It should be ok :)
Use strptime:
import datetime
today = datetime.datetime.now().date()
parsed = datetime.datetime.strptime("2018,02,14", "%Y,%m,%d").date()
print(today < parsed) # True
I am struggling to find the best way to convert the date input given by the user as mm/dd/yyyy to 3 variables. I am unable to split this because I receive an error since it is a 'float'.
>>> date=3/2/2016
>>> date.split('/')
Traceback (most recent call last):
File "<pyshell#152>", line 1, in <module> date.split('/')
AttributeError: 'float' object has no attribute 'split'
what do I need to add to this to make sure it doesn't evaluate the date with division?
def main():
date=input("Enter date mm/dd/yyyy: ")
I want the input date given as mm/dd/yyyy, and then a way to convert this to 3 variables as m=month d=day y=year
What's the best way to do this?
Try str.split:
>>> test_date = "05/12/2016"
>>> month, day, year = test_date.split('/')
>>> print(f"Month = {month}, Day = {day}, Year = {year}")
Month = 05, Day = 12, Year = 2016
I wrote this following piece of code and it works perfectly fine.
>>> date='3/2/2016'
>>> new=date.split('/')
>>> new
['3', '2', '2016']
>>>
>>> m,d,year=new
>>> m
'3'
>>> d
'2'
>>> year
'2016'
>>>
Like Jessica Smith has already pointed it out, date=3/2/2016 evaluates expressions and divides the numbers. It has to be of string string type to be split.
The error "'float' object has no attribute 'split'" suggests that type(date) == float in your example that implies that you are trying to run Python 3 code using Python 2 interpreter where input() evaluates its input as a Python expression instead of returning it as a string.
To get the date as a string on Python 2, use raw_input() instead of input():
date_string = raw_input("Enter date mm/dd/yyyy: ")
To make it work on both Python 2 and 3, add at the top of your script:
try: # make input() and raw_input() to be synonyms
input = raw_input
except NameError: # Python 3
raw_input = input
If you need the old Python 2 input() behavior; you could call eval() explicitly.
To validate the input date, you could use datetime.strptime() and catch ValueError:
from datetime import datetime
try:
d = datetime.strptime(date_string, '%m/%d/%Y')
except ValueError:
print('wrong date string: {!r}'.format(date_string))
.strptime() guarantees that the input date is valid otherwise ValueError is raised. On success, d.year, d.month, d.day work as expected.
Putting it all together (not tested):
#!/usr/bin/env python
from datetime import datetime
try: # make input() and raw_input() to be synonyms
input = raw_input
except NameError: # Python 3
raw_input = input
while True: # until a valid date is given
date_string = raw_input("Enter date mm/dd/yyyy: ")
try:
d = datetime.strptime(date_string, '%m/%d/%Y')
except ValueError: # invalid date
print('wrong date string: {!r}'.format(date_string))
else: # valid date
break
# use the datetime object here
print("Year: {date.year}, Month: {date.month}, Day: {date.day}".format(date=d))
See Asking the user for input until they give a valid response.
You could use .split('/') instead of .strptime() if you must:
month, day, year = map(int, date_string.split('/'))
It doesn't validate whether the values form a valid date in the Gregorian calendar.
Try:
def main():
month, day, year = [int(x) for x in raw_input("Enter date mm/dd/yyyy: ").split('/')]
print "Month: {}\n".format(month), "Day: {}\n".format(day), "Year: {}".format(year)
main()
Output:
Enter date mm/dd/yyyy: 03/09/1987
Month: 3
Day: 9
Year: 1987
I wrote a program in python(I'm a beginner still) that converts a date from numbers to words using dictionaries. The program is like this:
dictionary_1 = { 1:'first', 2:'second'...}
dictionary_2 = { 1:'January', 2:'February',...}
and three other more for tens, hundreds, thousands;
2 functions, one for years <1000, the other for years >1000;
an algorithm that verifies if it's a valid date.
In main I have:
a_random_date = raw_input("Enter a date: ")
(I've chosen raw_input for special chars. between numbers such as: 21/11/2014 or 21-11-2014 or 21.11.2014, only these three) and after verifying if it's a valid date I do not know nor did I find how to call upon the dictionaries to convert the date into words, when I run the program I want at the output for example if I typed 1/1/2015: first/January/two thousand fifteen.
And I would like to apply the program to a text document to seek the dates and convert them from numbers to words if it is possible.
Thank you!
You can split that date in list and then check if there is that date in dictionary like this:
import re
dictionary_1 = { 1:'first', 2:'second'}
dictionary_2 = { 1:'January', 2:'February'}
dictionary_3 = { 1996:'asd', 1995:'asd1'}
input1 = raw_input("Enter date:")
lista = re.split(r'[.\/-]', input1)
print "lista: ", lista
day = lista[0]
month = lista[1]
year = lista[2]
everything_ok = False
if dictionary_1.get(int(day)) != None:
day_print = dictionary_1.get(int(day))
everything_ok = True
else:
print "There is no such day"
if dictionary_2.get(int(month)) != None:
month_print = dictionary_2.get(int(month))
everything_ok = True
else:
print "There is no such month"
everything_ok = False
if dictionary_3.get(int(year)) != None:
year_print = dictionary_3.get(int(year))
everything_ok = True
else:
print "There is no such year"
everything_ok = False
if everything_ok == True:
print "Date: ", day_print, "/", month_print, "/", year_print #or whatever format
else:
pass
This is the output:
Enter date:1/2/1996
Date: first / February / asd
I hope this helps you.
Eventually you will need the re module. Learn to write a regular expression that can search strings of a particular format. Here's some code example:
with open("mydocument.txt") as f:
contents = f.read()
fi = re.finditer(r"\d{1,2}-\d{1,2}-\d{4}", contents)
This will find all strings that are made up of 1 or 2 digits followed by a hyphen, followed by another 1 or 2 digits followed by a hyphen, followed by 4 digits. Then, you feed each string into datetime.strptime; it will parse your "date" string and decide if it is valid according to your specified format.
Have fun!
i am writing a script in python that searches for strings and suposedly does different things when encounters strings.
import re, datetime
from datetime import *
f = open(raw_input('Name of file to search: ')
strToSearch = ''
for line in f:
strToSearch += line
patFinder = re.compile('\d{2}\/\d{2}\/\d{4}\sA\d{3}\sB\d{3}')
findPat1 = re.findall(patFinder, strToSearch)
# search only dates
datFinder = re.compile('\d{2}\/\d{2}\/\d{4}')
findDat = re.findall(datFinder, strToSearch)
nowDate = date.today()
fileLst = open('cels.txt', 'w')
ntrdLst = open('not_ready.txt', 'w')
for i in findPat1:
for Date in findDat:
Date = datetime.strptime(Date, '%d/%m/%Y')
Date = Date.date()
endDate = Date + timedelta(days=731)
if endDate < nowDate:
fileLst.write(i)
else:
ntrdLst.write(i)
f.close()
fileLst.close()
ntrdLst.close()
toClose = raw_input('File was modified, press enter to close: ')
so basically it searches for a string with dates and numbers and then same list but only dates, converts the dates, adds 2 years to each and compares, if the date surpass today's date, goes to the ntrdLst, if not, to fileLst.
My problem is that it writes the same list (i) multiple times and doesn't do the sorting.
i am fearly new to python and programming so i am asking for your help. thanks in advance
edit: -----------------
the normal output was this (without the date and if statement)
27/01/2009 A448 B448
22/10/2001 A434 B434
06/09/2007 A825 B825
06/09/2007 A434 B434
06/05/2010 A826 B826
what i would like is if i had a date that is after date.today() say like 27/01/2016 to write to another file and what i keep getting is the script printing this list 30x times or doesn't take to account the if statement.
(sorry, the if was indeed indented the last loop, i went wrong while putting it in here)
You're computing endDate in a loop, once for each date... but not doing anything with it in the loop. So, after the loop is over, you have the very last endDate, and you use only that one to decide which file to write to.
I'm not sure what your logic is supposed to be, but I'm pretty sure you want to put the if statement with the writes inside the inner loop.
If you do that, then if you have, say, 100 pattern matches and 25 dates, you'll end up writing 2500 strings--some to one file, some to the other. Is that what you wanted?
SOLVED
i gave it a little (A LOT) of thought about it and just got all together in one piece. i knew that there too many for loops but now i got it. Thanks anyway to you whom have reached a helping hand to me. I leave the code for anyone having a similar problem.
nowDate = date.today()
for line in sourceFile:
s = re.compile('(\d{2}\/\d{2}\/\d{4})\s(C\d{3}\sS\d{3})')
s1 = re.search(s, line)
if s1:
date = s1.group(1)
date = datetime.strptime(date, '%d/%m/%Y')
date = date.date()
endDate = date + timedelta(days=731)
if endDate <= nowDate:
fileLst.write(s1.group())
fileLst.write('\n')
else:
print ('not ready: ', date.strftime('%d-%m-%Y'))
ntrdLst.write(s1.group(1))
ntrdLst.write('\n')