python - password expiry - python-2.7

I am trying to add a password expiry on to my web application. The goal is for the user to change their password every 30 days with a notification of how many days are left before they have to change their password. I am trying to calculate the amount of days left using :
enter code here
import datetime
today = datetime.date.today()
expire = 30
day = today.strftime(' %d ')
daysLeft = (expire - day)
print today.strftime('you have '+ daysLeft +' days to change your password')
but am having issues because I am trying to use an integer and a string in the one sum. Any help would be greatly appreciated.

if you want to convert a string to an integer, use this syntax :
daysLeft = (expire - int(day))
if you want to convert an integer to a string, you can use this syntax :
today.strftime('you have '+ str(daysLeft) +' days to change your password')
But as André Schild said in the comments, you probably don't want to do it this way. You could just print your message without calling strftime, if the information you want to be displayed is on the days remaining only.

Related

Age checker Python3 18+

I need a programm on Pyhton3 to check if the user is 18+ or not.
Input: date of the birth. in 4 types of format (25/12/2000,25-12-2000,25.12.2000,25_12_2000)
if wrong print(wrong format)
Output: "welcome to system" or "sorry comeback when you will be 18+"
In case you need my stupid tries:
from datetime import datetime, date
def try_parsing_date(text):
for fmt in ('%d/%m/%Y', '%d.%m.%Y', '%d-%m-%Y', '%d_%m_%Y'):
try:
return datetime.strftime(text,fmt)
except ValueError:
pass
raise ValueError('no valid date format')
dob = input('Введите свой день рождения (дд/мм/гггг): ')
try_parsing_date(dob)
Maybe to deal with it wit regular expressions?
```re_age_checker= "^(0[1-9]|[12][0-9]|3[01])[- \/.,_](0[1-9]|1[012])[- \/.,_](19|20)\d\d"```
Your try was a good start, but you mixed up strftime with strptime; change that.
Maybe to deal with it wit regular expressions?
This is not advisable. After the above change, we can use the result of your function try_parsing_date to compute the 18th birthday and simply compare that to today's date:
dt = try_parsing_date(dob)
import time
# compute the 18th birthday:
d = date.fromtimestamp(time.mktime((dt.year+18, dt.month, dt.day, *(0,)*6)))
if d <= date.today():
print("welcome to system")
else:
print("sorry comeback when you will be 18+")

What is the best way to schedule `whenever` task in rails in midnight usa?

We have a Rails 4 application .
What is the best way to schedule whenever task in rails in midnight usa with daylight saving ?
We need to send email at 11.58pm in night of a day's report .
We are using tzinfo gem
TZInfo::Timezone.get('America/Denver').local_to_utc(Time.parse('11:58pm')).strftime('%H:%M%p')
is not sending email at the time .
This works around the timezone issue, server is at UTC and users in another time zone (with daylight saving time). define a local action and use in cronjob.
schedule.rb
require "tzinfo"
def local(time)
TZInfo::Timezone.get('America/Denver').local_to_utc(Time.parse(time))
end
every :sunday, at: local("11:58 pm") do
#your email sending task
end
hope it will help you.
Rehan's answer was SO great! In my use case I ran into an issue where the time zone conversion also changed the day of the week the task would be scheduled for.
Perhaps there is an easier way but here is what I did.
The timezone conversion we needed would only advance the weekday.
If your use case requires the weekday to be retreated then you will need to edit this, but it should be an easy fix.
def local(time, est_weekday = nil)
days = [:sunday, :monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday]
local_time = Time.parse(time)
utc_time = TZInfo::Timezone.get('America/New_York').local_to_utc(local_time)
utc_time_formatted = utc_time.strftime("%I:%M %p")
if est_weekday && days.include?(est_weekday.downcase.to_sym)
#extract intended wday for ruby datetime and assign
weekday_index = days.index(est_weekday.downcase.to_sym)
#get placeholder wday from desired EST day/time
temp_est_weekday_index = local_time.wday
#get placeholder wday from adjusted UTC day/time
temp_utc_weekday_index = utc_time.wday
#has the conversion to UTC advanced the wday?
weekday_advances = temp_utc_weekday_index != temp_est_weekday_index
#adjust wday index if timezone conversion has advanced weekday
weekday_index += 1 if weekday_advances
weekday = days[weekday_index]
return {time: utc_time_formatted, day: weekday || nil }
else
return utc_time_formatted
end
end

Xively read data in Python

I have written a python 2.7 script to retrieve all my historical data from Xively.
Originally I wrote it in C#, and it works perfectly.
I am limiting the request to 6 hour blocks, to retrieve all stored data.
My version in Python is as follows:
requestString = 'http://api.xively.com/v2/feeds/41189/datastreams/0001.csv?key=YcfzZVxtXxxxxxxxxxxORnVu_dMQ&start=' + requestDate + '&duration=6hours&interval=0&per_page=1000' response = urllib2.urlopen(requestString).read()
The request date is in the correct format, I compared the full c# requestString version and the python one.
Using the above request, I only get 101 lines of data, which equates to a few minutes of results.
My suspicion is that it is the .read() function, it returns about 34k of characters which is far less than the c# version. I tried adding 100000 as an argument to the ad function, but no change in result.
Left another solution wrote in Python 2.7 too.
In my case, got data each 30 minutes because many sensors sent values every minute and Xively API has limited half hour of data to this sent frequency.
It's general module:
for day in datespan(start_datetime, end_datetime, deltatime): # loop increasing deltatime to star_datetime until finish
while(True): # assurance correct retrieval data
try:
response = urllib2.urlopen('https://api.xively.com/v2/feeds/'+str(feed)+'.csv?key='+apikey_xively+'&start='+ day.strftime("%Y-%m-%dT%H:%M:%SZ")+'&interval='+str(interval)+'&duration='+duration) # get data
break
except:
time.sleep(0.3)
raise # try again
cr = csv.reader(response) # return data in columns
print '.'
for row in cr:
if row[0] in id: # choose desired data
f.write(row[0]+","+row[1]+","+row[2]+"\n") # write "id,timestamp,value"
The full script you can find it here: https://github.com/CarlosRufo/scripts/blob/master/python/retrievalDataXively.py
Hope you might help, delighted to answer any questions :)

How do you remove seconds and milliseconds from a date time string in python

How I can convert a date in format "2013-03-15 05:14:51.327" to "2013-03-15 05:14", i.e. removing the seconds and milliseconds. I don't think there is way in Robot frame work. Please let me know if any one have a solution for this in python.
Try this (Thanks Blender!)
>>> date = "2013-03-15 05:14:51.327"
>>> newdate = date.rpartition(':')[0]
>>> print newdate
2013-03-15 05:14
In Robotframework the most straightforward way would be to user Split String From Right from the String library library:
${datestring}= Set Variable 2019-03-15 05:14:51.327
${parts}= Split String From Right ${datestring} : max_split=1
# parts is a list of two elements - everything before the last ":", and everything after it
# take the 1st element, it is what we're after
${no seconds}= Get From List ${parts} 0
Log ${no senods} # 2019-03-15 05:14

python - UTC minus 15 minutes in 13 digit timestamp format

I have scratched my brains enough to find my last resort here . I am calling an API which takes values like below for the lastUpdatedTime paramter :
lastUpdatedTime : 1499591547769
lastUpdatedTime : 1499591547770
So i assume the above values are converted to miliseconds since there are 13 digits (1499591547770 & 1499591547769).
Below is what i want to do in simple english .
Get the UTC time now and subtract 15 minutes from it .
Send that value to the API and fetch the data.
My problem is time conversion .
Below is what i am doing in python.
update_time = (datetime.utcnow() - timedelta(minutes=15)).strftime('%m/%d/%Y %H:%M:%S')
update_time_check = (calendar.timegm(time.strptime(update_time, '%m/%d/%Y %H:%M:%S')))*1000
The value for the above is something like 1502247759000
When i send that value (lastUpdatedTime = 1502247759000) to the API , i get a blank result set .
Please let me know if my steps are correct in generating the timestamp which the API is expecting .
Thanks in advance.