Comparing two time types in Python - python-3.x

I'm trying to make a function that checks the current time, and tells me if it's before or after sunrise, sunset, dusk, dawn and noon.
But I'm a bit stuck in how to compare the time types I get :(
Can anyone help me out?
This is my code:
now = datetime.now()
now_time = now.time()
print ('\nTime now is %s \n' % now_time)
city_name = 'Stockholm'
a = Astral()
a.solar_depression = 'civil'
city = a[city_name]
print('Information for %s/%s\n' % (city_name, city.region))
timezone = city.timezone
print('Timezone: %s' % timezone)
print('Latitude: %.02f; Longitude: %.02f\n' % \
(city.latitude, city.longitude))
today = datetime.strptime(time.strftime("%Y-%m-%d"), '%Y-%m-%d')
sun = city.sun(date=datetime.date(today), local=True)
dawn = str(sun['dawn'])[11:-6]
sunrise = str(sun['sunrise'])[11:-6]
noon = str(sun['noon'])[11:-6]
sunset = str(sun['sunset'])[11:-6]
dusk = str(sun['dusk'])[11:-6]
print('Dawn: %s' % dawn)
print('Sunrise: %s' % sunrise)
print('Noon: %s' % noon)
print('Sunset: %s' % sunset)
print('Dusk: %s \n' % dusk)
if now_time > datetime.strptime(dawn, '%H:%M:%S'):
print ('Time is after dawn')
else:
print ('Time is before dawn')
It returns this:
Traceback (most recent call last):
File "test.py", line 63, in <module>
If now_time > datetime.strptime(dawn, '%H:%M:%S'):
TypeError: can't compare datetime.time to datetime.datetime

To extract a time object from a datetime object, use the datetime.time() function or the datetime.timetz() function. The latter will retain timezone information, while the former will not.
So change the problem line to this:
if now_time > datetime.strptime(dawn, '%H:%M:%S').time():

Related

Unable to a convert given date to a required date format that is coming from the df['dateformat'] In python

MeetingDate = datetime.datetime(2020,5,11)
df = pd.read_csv('request.csv')
dateformatsXpaths = df['dateformat']
MeetingDateXpaths = df['WebCfg_MtgDate_xpath']
urls = df['url']
fcids = df['fcid']
for url in urls:
driver.get(url)
agendaMeetingdateformat = MeetingDate.strftime(df['dateformat'])
meeting =df['WebCfg_MtgDate_xpath'].replace('*', agendaMeetingdateformat)
my_element = driver.find_element_by_xpath(meeting).text
if my_element == agendaMeetingdateformat :
print('valid Meeting date')
else:
print('Invalid Meeting date')
driver.close()
I want to convert the given date to the date format that is coming from the df['dateformat'],but its throwing following error
Traceback (most recent call last):
File "C:\Users\sameer\PycharmProjects\Python\MeetingDateFinder.py", line 32, in <module>
agendaMeetingdateformat = MeetingDate.strftime(df['datefromat'])
TypeError: strftime() argument 1 must be str, not Series

Python Download Latest CSV from FTP server [duplicate]

I am using ftplib to connect to an ftp site. I want to get the most recently uploaded file and download it. I am able to connect to the ftp server and list the files, I also have put them in a list and got the datefield converted. Is there any function/module which can get the recent date and output the whole line from the list?
#!/usr/bin/env python
import ftplib
import os
import socket
import sys
HOST = 'test'
def main():
try:
f = ftplib.FTP(HOST)
except (socket.error, socket.gaierror), e:
print 'cannot reach to %s' % HOST
return
print "Connect to ftp server"
try:
f.login('anonymous','al#ge.com')
except ftplib.error_perm:
print 'cannot login anonymously'
f.quit()
return
print "logged on to the ftp server"
data = []
f.dir(data.append)
for line in data:
datestr = ' '.join(line.split()[0:2])
orig-date = time.strptime(datestr, '%d-%m-%y %H:%M%p')
f.quit()
return
if __name__ == '__main__':
main()
RESOLVED:
data = []
f.dir(data.append)
datelist = []
filelist = []
for line in data:
col = line.split()
datestr = ' '.join(line.split()[0:2])
date = time.strptime(datestr, '%m-%d-%y %H:%M%p')
datelist.append(date)
filelist.append(col[3])
combo = zip(datelist,filelist)
who = dict(combo)
for key in sorted(who.iterkeys(), reverse=True):
print "%s: %s" % (key,who[key])
filename = who[key]
print "file to download is %s" % filename
try:
f.retrbinary('RETR %s' % filename, open(filename, 'wb').write)
except ftplib.err_perm:
print "Error: cannot read file %s" % filename
os.unlink(filename)
else:
print "***Downloaded*** %s " % filename
return
f.quit()
return
One problem, is it possible to retrieve the first element from the dictionary? what I did here is that the for loop runs only once and exits thereby giving me the first sorted value which is fine, but I don't think it is a good practice to do it in this way..
For those looking for a full solution for finding the latest file in a folder:
MLSD
If your FTP server supports MLSD command, a solution is easy:
entries = list(ftp.mlsd())
entries.sort(key = lambda entry: entry[1]['modify'], reverse = True)
latest_name = entries[0][0]
print(latest_name)
LIST
If you need to rely on an obsolete LIST command, you have to parse a proprietary listing it returns.
Common *nix listing is like:
-rw-r--r-- 1 user group 4467 Mar 27 2018 file1.zip
-rw-r--r-- 1 user group 124529 Jun 18 15:31 file2.zip
With a listing like this, this code will do:
from dateutil import parser
# ...
lines = []
ftp.dir("", lines.append)
latest_time = None
latest_name = None
for line in lines:
tokens = line.split(maxsplit = 9)
time_str = tokens[5] + " " + tokens[6] + " " + tokens[7]
time = parser.parse(time_str)
if (latest_time is None) or (time > latest_time):
latest_name = tokens[8]
latest_time = time
print(latest_name)
This is a rather fragile approach.
MDTM
A more reliable, but a way less efficient, is to use MDTM command to retrieve timestamps of individual files/folders:
names = ftp.nlst()
latest_time = None
latest_name = None
for name in names:
time = ftp.voidcmd("MDTM " + name)
if (latest_time is None) or (time > latest_time):
latest_name = name
latest_time = time
print(latest_name)
For an alternative version of the code, see the answer by #Paulo.
Non-standard -t switch
Some FTP servers support a proprietary non-standard -t switch for NLST (or LIST) command.
lines = ftp.nlst("-t")
latest_name = lines[-1]
See How to get files in FTP folder sorted by modification time.
Downloading found file
No matter what approach you use, once you have the latest_name, you download it as any other file:
with open(latest_name, 'wb') as f:
ftp.retrbinary('RETR '+ latest_name, f.write)
See also
Get the latest FTP folder name in Python
How to get FTP file's modify time using Python ftplib
Why don't you use next dir option?
ftp.dir('-t',data.append)
With this option the file listing is time ordered from newest to oldest. Then just retrieve the first file in the list to download it.
With NLST, like shown in Martin Prikryl's response,
you should use sorted method:
ftp = FTP(host="127.0.0.1", user="u",passwd="p")
ftp.cwd("/data")
file_name = sorted(ftp.nlst(), key=lambda x: ftp.voidcmd(f"MDTM {x}"))[-1]
If you have all the dates in time.struct_time (strptime will give you this) in a list then all you have to do is sort the list.
Here's an example :
#!/usr/bin/python
import time
dates = [
"Jan 16 18:35 2012",
"Aug 16 21:14 2012",
"Dec 05 22:27 2012",
"Jan 22 19:42 2012",
"Jan 24 00:49 2012",
"Dec 15 22:41 2012",
"Dec 13 01:41 2012",
"Dec 24 01:23 2012",
"Jan 21 00:35 2012",
"Jan 16 18:35 2012",
]
def main():
datelist = []
for date in dates:
date = time.strptime(date, '%b %d %H:%M %Y')
datelist.append(date)
print datelist
datelist.sort()
print datelist
if __name__ == '__main__':
main()
I don't know how it's your ftp, but your example was not working for me. I changed some lines related to the date sorting part:
import sys
from ftplib import FTP
import os
import socket
import time
# Connects to the ftp
ftp = FTP(ftpHost)
ftp.login(yourUserName,yourPassword)
data = []
datelist = []
filelist = []
ftp.dir(data.append)
for line in data:
col = line.split()
datestr = ' '.join(line.split()[5:8])
date = time.strptime(datestr, '%b %d %H:%M')
datelist.append(date)
filelist.append(col[8])
combo = zip(datelist,filelist)
who = dict(combo)
for key in sorted(who.iterkeys(), reverse=True):
print "%s: %s" % (key,who[key])
filename = who[key]
print "file to download is %s" % filename
try:
ftp.retrbinary('RETR %s' % filename, open(filename, 'wb').write)
except ftplib.err_perm:
print "Error: cannot read file %s" % filename
os.unlink(filename)
else:
print "***Downloaded*** %s " % filename
ftp.quit()

How to recursively ask for input when given wrong date format for two raw input and continue the operation in python

I'm trying to get two dates as input and convert is epoch time, but i need the two different dates given as input to be validated in correct format else recursively ask for correct input.
from datetime import date
import datetime
start_date = datetime.datetime.strptime(raw_input('Enter Start date in the format DD-MM-YYYY: '), '%d-%m-%Y')
end_date = datetime.datetime.strptime(raw_input('Enter Start date in the format DD-MM-YYYY: '), '%d-%m-%Y')
epoch_date = datetime.datetime(1970,1,1)
diff1 = (start_date - epoch_date).days
diff2 = (end_date - epoch_date).days
epoch1 = (diff1 * 86400)
epoch2 = (diff2 * 86400)
print('\nPTime_Start: %i' % diff1),
print("&"),
print('PTime_End: %i' % diff2)
print('Epoch_Start: %i' % epoch1),
print("&"),
print('Epoch_End: %i' % epoch2)
First of all, you are using Python 3.x and Python 3.x does not have any function that is called "raw_input()". It has been changed to "input()".
def take_date_input():
input_date = input('Enter date in the format DD-MM-YYYY: ')
try:
one_date = datetime.datetime.strptime(input_date, '%d-%m-%Y')
except ValueError:
return take_date_input()
return one_date
You can do this if you really want recursiveness in your code but it would be better with while loop.

My program is supposed to output answers into a csv file with a certain format

This is the code
import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print(mylist[0])
file = open('Date.txt', 'a')
file.write(mylist)
file.close()
global timestable
global text
def timestable():
global name
name = input("What is your name? ")
global number
number = int(input("Insert a number you want the 12 times table for: "))
global multiply
for multiply in range(1,13):
print(number,"x",multiply,"=",number*multiply)
text()
def text():
file=open("list.csv","a")
file.write("The date is," + today + "\nTimestables are:\n" + number + "x" + multiply + "=" + number*multiply + "\nYour name is, " + name)
file.close()
text()
timestable()
The problem is that nothing is being outputted into the file and its supposed to be outputted with a certain format also.
The error is
Traceback (most recent call last):
File "D:\Python\Code\Lesson Task Code.py", line 9, in <module>
file.write(mylist)
TypeError: must be str, not list
Instead of datetime.date.today() you probably want to tryout time.strftime("%Y-%m-%d"):
from time import strftime
today = strftime("%Y-%m-%d")
print(today)
with open('Date.txt', 'a') as file:
file.write(today+"\n")

Ignore unconverted data from date-time stamp when using strptime

A third party API returns me a CSV data containing date time stamp like this:
dtval = '2016-10-14 05:09:30+00:00'
I have to convert it in the format : mm/dd/yyyy.
Here I'm not sure about last +XX:XX of directive:
datetime.datetime.strptime(dtval, "%Y-%m-%d %H:%M:%S+XX:XX").strftime('%m/%d/%Y')
I tried followings but did not work:
>>>datetime.datetime.strptime('2016-10-14 05:09:30+00:00', '%Y-%m-%d %H:%M:%S')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/_strptime.py", line 500, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib/python3.5/_strptime.py", line 340, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: +00:00
>>>datetime.datetime.strptime('2016-10-14 05:09:30+00:00', "%Y-%m-%d %H:%M:%S%z")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/_strptime.py", line 500, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib/python3.5/_strptime.py", line 337, in _strptime
(data_string, format))
ValueError: time data '2016-10-14 05:09:30+00:00' does not match format '%Y-%m-%d %H:%M:%S+%z'
Is there any option in the Python3.4+'s datetime module to ignore remainging unconverted data?
I gone through this but did not find any such option
After a little bit research I found this fix in django's source code :
class FixedOffset(tzinfo):
"""
Fixed offset in minutes east from UTC. Taken from Python's docs.
Kept as close as possible to the reference version. __init__ was changed
to make its arguments optional, according to Python's requirement that
tzinfo subclasses can be instantiated without arguments.
"""
def __init__(self, offset=None, name=None):
if offset is not None:
self.__offset = timedelta(minutes=offset)
if name is not None:
self.__name = name
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(self, dt):
return timedelta(0)
def get_timezone(offset):
"""
Returns a tzinfo instance with a fixed offset from UTC.
"""
if isinstance(offset, timedelta):
offset = offset.seconds // 60
sign = '-' if offset < 0 else '+'
hhmm = '%02d%02d' % divmod(abs(offset), 60)
name = sign + hhmm
return FixedOffset(offset, name)
def custom_strptime(self, value):
"""Parses a string and return a datetime.datetime.
This function supports time zone offsets. When the input contains one,
the output uses a timezone with a fixed offset from UTC.
Raises ValueError if the input is well formatted but not a valid datetime.
Returns None if the input isn't well formatted.
"""
datetime_re = re.compile(
r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})'
r'[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})'
r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?'
r'(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$'
)
match = datetime_re.match(value)
if match:
kw = match.groupdict()
if kw['microsecond']:
kw['microsecond'] = kw['microsecond'].ljust(6, '0')
tzinfo = kw.pop('tzinfo')
if tzinfo == 'Z':
tzinfo = utc
elif tzinfo is not None:
offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0
offset = 60 * int(tzinfo[1:3]) + offset_mins
if tzinfo[0] == '-':
offset = -offset
tzinfo = get_timezone(offset)
kw = {k: int(v) for k, v in kw.items() if v is not None}
kw['tzinfo'] = tzinfo
return datetime.datetime(**kw)

Resources