Python attendance analysis

Source: Internet
Author: User
Tags timedelta

The last Ruby attendance that, because every day email, personnel feel bored, just now in toss Python, so with this rewrite ...


This e-mail, can send attachments, pictures ... Record it


#!/usr/bin/pythonimport datetimeimport mysqldbimport smtplib  from  email.mime.multipart import mimemultipart  from email.mime.text import  mimetext  from email.mime.image import mimeimage  csv_str =  ' datetime,name,start,over,hour\n ' name = {1: "Mei.han",  2: "Xing.mei",  3: "You.yao",  6: " Zing.ma ",  9:" Jing.cai "}csv_file = "/tmp/check_in.csv "Def send_mail (filename=[],  Picname=[], content_txt= ',  content_html= '):   smtpserver =  ' smtp.163.com '     username =  ' [email protected] '     password =   ' 123123 '         msg = mimemultipart ()      msg[' Subject '] =  ' check_in '     msg[' from '] =  ' [email  Protected] "  msg[' to '] = "[email protected]"     # attchment  if len (filename)  >  0:    for i in filename:      att  = mimetext (Open (i,  ' RB '). Read (),  ' base64 ',  ' gf2312 ')          att["Content-type"] =  ' Application/octet-stream '          att["content-disposition"] =  ' attachment; filename= "%s" '  % i.split ('/') [- 1]      msg.attach (ATT)   # attchment picture  if  len (Picname)  > 0 and content_html !=  ":     for  i in range (0,len (picname)):       #content_html  =  ' < b>some <i>html</i> text</b> and an image.<br><br>good! '  % i        msg_content_html = mimetext (Content_ HTML, ' HTML ', ' gb2312 ')         msg.attach (msg_content_html)            with open (picname[i],  ' RB ')  as f:         msgimage = mimeimage (F.read ())                msgimage.add_header (' Content-ID ',  ' <image% S> '  %  (i + 1))         msg.attach (MsgImage)     # content text      if content_txt ! =  ':     msg_content_txt = mimetext (content_txt,_subtype= ' plain ', _charset= ' gb2312 ')      msg.attach (msg_content_txt) # content html     if content_html !=  '  and len (picname)  == 0:    msg_content_html  = mimetext (content_html,_subtype= ' HTML ', _charset= ' gb2312 ')      msg.attach ( msg_content_html)     smtp = smtplib. SMTP ()     smtp.connect (' smtp.163.com ')     smtp.starttls ()   # Ssl send  smtp.login (Username, password)     smtp.sendmail (msg[' from '),  msg[' to '], msg.as_string ())     smtp.quit () &NBSP;&NBSP;DEF&NBSP;CHECK_KQ (kq_time ):  tmp_list = []  csv_tmp =  '   work = false   try:    conn = mysqldb.connect (host= ' 192.168.2.2 ', user= ' KQ ', passwd= ' 123123 ', db= ' test ', port=3306)     cur = conn.cursor ()        for i in name.keys ():       max_time = kq_time +  " 23:00:00"        min_time = kq_time +  " 06:00:00"       cur.execute ("Select * from kqtime where userid=%s and time>\ '%s\ '  and  Time<\ '%s\ '  %  (i,min_time,max_time)       kqtime =  Cur.fetchall ()         for x,y,z in kqtime:  #num,  time, userid        tmp_list.append (y)              if len (tmp_list)  == 0:         csv_tmp = csv_tmp +  ("%s,%s,,, 0"  %  (kq_time,name[i ])  +  "\ n"       elif len (tmp_list)  == 1:        &Nbsp;if int (Tmp_list[0].strftime ("%H"))  < 12:           csv_tmp = csv_tmp +  ("%s,%s,%s,,0"  %  (kq_time,name[i],tmp_list [0].strftime ("%h:%m:%s"))  +  "\ n"         else:           csv_tmp = csv_tmp +  ("%s,%s,,%s,0"  %   (Kq_time,name[i],tmp_list[0].strftime ("%h:%m:%s"))  +  "\ n"          work = True      else:       &NBSP;&NBSP;HOUR_STR&NBSP;=&NBSP;STR (Max (tmp_list)  - min (tmp_list))          hour = int (Hour_str.split (': ') [0])          Sec = int (Hour_str.split (': ') [1])         if hour  > 3:          hour -= 1                   if sec < 15:           hour += 0.0          elif 15 <= sec < 45:           hour += 0.5        elif  sec >= 45:          hour += 1.0         work = True         csv_tmp = csv_tmp +  ("%s,%s,%s,%s,%s"  %  (Kq_time,name[i],min (tmp_list). Strftime ("%h:%m:%s"), Max (tmp_list) strftime ("%h:%m:%s"), hour)  +  "\ n"          tmp_list =&nbsP []      cur.close ()     conn.close ()   except:     pass  if work:    return csv_tmp  else:     return  ' For i in range (1,8) [::-1]:  #一周分析一次 &NBSP;&NBSP;DAY_KQ &NBSP;=&NBSP;CHECK_KQ ((Datetime.datetime.now ()  - datetime.timedelta (days=i)). Strftime ("%y-%m-%d"))   if day_kq !=  ':    csv_str = csv_str +  CHECK_KQ ((Datetime.datetime.now ()  - datetime.timedelta (days=i)). Strftime ("%y-%m-%d"))  +  "\ N "With open (csv_file,  ' W ')  as f:  f.write (CSV_STR) send_mail (Filename=[csv_file],  content_txt= "check_in") Os.remove (Csv_file)


Python attendance analysis

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.