Date input format? [duplicate] - python

This question already has answers here:
AttributeError: 'datetime' module has no attribute 'strptime'
(5 answers)
Closed 5 years ago.
I have code like this:
import time
import datetime
def dates():
date1 = str(input('Date start: '))
try:
dt_start = datetime.strptime(date1, '%d, %m, %Y')
except ValueError:
print ("Incorrect format")
date2 = str(input('Date end: '))
try:
dt_end = datetime.strptime(date2, '%d, %m, %Y')
except ValueError:
print ("Incorrect format")
if date1 > date2:
print("Error!")
dates()
And I want to define date input format like d.m.Y.
For example, when I input "17.12.1995". I got error:
'module' object has no attribute 'strptime'.
How to define user input format?

datetime is a module, there is a class with the same name (datetime) within it and that class has a class method strptime(). You need to either call it like:
dt_start = datetime.datetime.strptime(date1, '%d, %m, %Y')
Or to change your import statement:
from datetime import datetime
so that it imports only the datetime class to your current namespace.

Related

Error : strptime() argument 1 must be str, not int

I am trying to substract two times and getting an error. In below total error is coming up
if result[0]['outTime'] != None:
type = "bothPunchDone"
FMT = '%H:%M:%S'
total= datetime.strptime(result[0]['outTime'], FMT) - datetime.strptime(result[0]['inTime'], FMT)
I tried but not able to solve the issue.
from datetime import datetime
result = datetime.now().strftime("%H:%M:%S")
if result != None:
type = "bothPunchDone"
FMT = '%H:%M:%S'
total= datetime.strptime(result, FMT) - datetime.strptime(result, FMT)
print(total)
is working for me. Try to check the type of result[0]['outTime']

Flatlib use current date and time

Can someone help with me this?
I am using Flatlib to compute planet positions, but the code for entering the date and time for computation is fixed, so you have to update it each time.
Is there a way to using datetime.now() [or another way] to complete the fields in the Datetime() automatically? I can't get the code in the date = Datetime() to accept any form of datetime code.
I looking to get Datetime() to accept month/day/year and hour:minute:second format eg (08/24/2018, 21:17:00)
With the below code i get the following error:
C:\Users\famil>C:\Users\famil\Desktop\flatlib_working_degree.py
('{0.month}/{0.day}/{0.year}', '21:15:41')
Traceback (most recent call last):
File "C:\Users\famil\Desktop\flatlib_working_degree.py", line 13, in
date = Datetime(x)
File "C:\Users\famil\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flatlib\datetime.py", line 177, in init
self.date = Date(date, calendar)
File "C:\Users\famil\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flatlib\datetime.py", line 76, in init
self.jdn = int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'
from flatlib.datetime import Datetime
from flatlib.geopos import GeoPos
from flatlib.chart import Chart
from flatlib import const
import datetime
# set date and time to now
now = datetime.datetime.now()
x = '{0.month}/{0.day}/{0.year}, {0.hour}:{0.minute}:{0.second}'.format(now)
print(x)
date = Datetime(x)
pos = GeoPos('53n15', '2e31')
chart = Chart(date, pos, hsys=const.HOUSES_PLACIDUS, IDs=const.LIST_OBJECTS)
# calculate body and degree value
asc = chart.get(const.ASC)
print(asc, asc.lon)
sun = chart.get(const.SUN)
print(sun, sun.lon, sun.movement())
moon = chart.get(const.MOON)
Flatlib's Datetime demands 2 separate inputs for date and time, as you can check here: Github: flatlib/datetime.py
.
def __init__(self, date, time=0, utcoffset=0, calendar=GREGORIAN):
But your code has only datetime 1 argument, separated by comma. That's incorrect:
now = datetime.datetime.now()
date = Datetime(now.strftime("%Y/%m/%d, %H:%M"))
You should write it like this:
now = datetime.datetime.now()
date = Datetime(now.strftime("%Y/%m/%d"), now.strftime('%H:%M'))

Python - TypeError: object of type 'NoneType' has no len()

I wrote a code that strips two values from a set of 50 items from a website and stored them into a list. However, when I check to see how many values there are via len() I get the following error:
TypeError: object of type 'NoneType' has no len()
This is my code:
from datetime import datetime
response = links
def get_links(response):
list_links = []
for i in range(len(response)):
url = response[i].select('a')[0]['href']
date = datetime.strptime(response[i].select('span.field-content')[1].text, '%A, %B %d, %Y')
list_links.append((url, date))
get_links(response)
page = get_links(response)
assert len(page) == 50
any ideas?
Your get_links function does not return anything add a return statement to it + iterating through the list is more optimal
here is an improved version of your code with the return statement
def get_links(response):
list_links = []
for link in response:
url = link.select('a')[0]['href']
date = datetime.strptime(link.select('span.field-content')[1].text, '%A, %B %d, %Y')
list_links.append((url, date))
return list_links

Error in generating list of dates

I have a python script
import urllib2
from bs4 import BeautifulSoup
import requests
import csv
from datetime import datetime
from datetime import date
from datetime import timedelta
def generateDateList(date,month,year):
today = date(year, month, date)
arrDates = []
for i in range(0,5):
arrDates.append(datetime.strftime(today + timedelta(days=i),"%d-%m-%y"))
return arrDates
print generateDateList(4,12,2017)
But i get this error-
Traceback (most recent call last):
File "test.py", line 17, in <module>
print generateDateList(4,12,2017)
File "test.py", line 11, in generateDateList
today = date(year, month, date)
TypeError: 'int' object is not callable
Why is it failing? I substituted the function with values and it worked. Should i convert the function inputs to integer again?
This line - def generateDateList(date,month,year):
The name of the first argument date shadows the name date imported at the top. You need to rename the argument to something like day inside your function.
As written, date is actually an integer you pass to the function, and calling it results in an error you are seeing.
Two options.
Option No.1 (import datetime):
import datetime
def generateDateList(date, month, year):
today = datetime.date(year, month, date)
arrDates = []
for i in range(0,5):
arrDates.append(datetime.datetime.strftime(today + datetime.timedelta(days=i),"%d-%m-%y"))
return arrDates
print generateDateList(4, 12, 2017)
Option No.2 (rename date parameter to day):
from datetime import datetime
from datetime import date
from datetime import timedelta
def generateDateList(day,month,year):
today = date(year, month, day)
arrDates = []
for i in range(0,5):
arrDates.append(datetime.strftime(today + timedelta(days=i),"%d-%m-%y"))
return arrDates
print generateDateList(4,12,2017)
The problem is the fact you have a parameter with the same name of the date() function.

ValueError: unconverted data remains: 00:00:00

I have problem in convert date time.
Here is my code:
#api.multi
def action_confirm(self):
if picking.state not in ['cancel', 'draft']:
for schedule_delivery in sorted_key:
print "line 105: ", schedule_delivery
dup_picking = picking.copy()
if shift == "afternoon":
date_object = datetime.strptime(schedule_delivery, '%Y-%m-%d')
print "Line 146", date_object
# raise EnvironmentError
tanggal = datetime.strftime(date_object, "%Y-%m-%d") + ' 06:00:00'
print "Line 145", tanggal
dup_picking.min_date = tanggal
else:
dup_picking.min_date = schedule_delivery
Error:
date_object = datetime.strptime(schedule_delivery, '%Y-%m-%d')
File "/usr/lib/python2.7/_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: 00:00:00
You can use this line of code-
date_object = datetime.strptime(str(schedule_delivery), '%Y-%m-%d %H:%M:%S')
i know its was asked a long time ago, i hope its still relevant.
in order to avoid the remains of the time format you need to convert your datetime to date
this is the code that solved this issue for me:
self.start_date=str((datetime.strptime(str(self.start_date), '%Y-%m-%d')+timedelta(nDays)).date())
Blockquote
Change the date to a pandas date:
Time object e.g
a = pd.to_datetime(df['date']).apply(lambda x: x.date())
Then
date_object = datetime.strptime(str(schedule_delivery), '%Y-%m-%d')

Categories

Resources