python 总结

0.  python模块

import requests, json, time, random, re

from retrying import retry

from random_ip_01 import proxy_ip_01

from random_UA_01 import random_ua_01

from random_UA import random_ua

from selenium import webdriver

from selenium.webdriver.common.proxy importProxy

from selenium.webdriver.common.proxy importProxyType

from bs4 import BeautifulSoup

import urllib.parse

from lxml import etree

from collections import OrderedDict

from pyexcel_xls import get_data

from pyexcel_xls import save_data

import pymysql

import pandas as pd

import os

import datetime

import time

 

1.保留小数

In [3]: b= round(a,2)

 

In [4]: b

Out[4]:5.02

 

In [5]: b= round(a,1)

 

In [6]: b

Out[6]:5.0

 

In [7]: c= float('%.2f' % a)

 

In [8]: c

Out[8]:5.02

 

In [9]:

 

 

2. 加密解密

 

In [1]: import hashlib

 

In [2]: a = '42745692018-01-17 21:35:20没发现啥大毛病用了一个多星,期,玩游戏有点儿热,所以3d大型单机啥的,时间不要太长。'

 

In [3]: m = hashlib.md5()

 

In [5]: m.update(a)

 

In [6]: b = m.hexdigest()

 

In [7]: b

Out[7]: '8a5d7a0e580e2f8259bb9580cd9f6d73'

 

 

过长字符串经加密后 变短,相应的 占用内存也变小


2.正则匹配 提取

wechat = re.findall(r"\[2017(.*?)liu456",content, re.DOTALL)

re.DOTALL  去除字符串换行符,否则有时匹配不出来内容

3. json.loads 提取

goods_list = '{"items":' +re.findall(r'items":(.*?),"current_page', goods_list_html,re.DOTALL)[0] + '}'

all_goods = json.loads(goods_list)['items']

4. beautifulsoup4 提取

 html20 =re.findall(r'''score">(.*?)</ul>''', res2.text, re.DOTALL)

 html2 = '<ul class="score">' +html20[0] + '</ul>'

soup2 = BeautifulSoup(html2, 'lxml')

 print('月销量=',month_num)

   # 描述

 escribe = soup2.select('b')[0].get_text().strip()

 print('描述相符=', escribe,  type(escribe))

 

4.1 注意 提取方式选择

Selenium 提取时  page = driver.page_source  (str)   最好用 beautiful4 提取

soup = BeautifulSoup(hhh, 'lxml')

           print(soup)

           all_list = soup.find_all('tr')

           for i in range(len(all_list)):

                one_day = all_list[i]

                # 时间

                datetime =one_day.find_all('td')[0].get_text()

                print(datetime)

                # 开盘价

                s_price =one_day.find_all('td')[1].get_text()

                # 收盘价

Resquests 提取时response = requests.get(url=url) content = response.text  用xpath提取

glh = re.findall(r'''<dlclass=\\"item(.*?)<div class=\\"pagination''', response1,re.DOTALL)

print(glh)

goods_list_html = '<divclass="hahaha"><dl class=\"item' + glh[0]

# print(goods_list_html)

html = etree.HTML(goods_list_html)

goods_list = html.xpath('//dl')

for one_goods in goods_list:

   print('\n')

   time.sleep(random.uniform(1, 3))

   title1 = one_goods.xpath('./dd[1]/a/text()')[0].strip()

 

 

 

4.5. xpath 提取

from lxml import etree

 

glh = re.findall(r'''<dlclass=\\"item(.*?)<div class=\\"pagination''', response1,re.DOTALL)

print(glh)

goods_list_html = '<divclass="hahaha"><dl class=\"item' + glh[0]

# print(goods_list_html)

html = etree.HTML(goods_list_html)

goods_list = html.xpath('//dl')

for one_goods in goods_list:

   print('\n')

   time.sleep(random.uniform(1, 3))

   title1 = one_goods.xpath('./dd[1]/a/text()')[0].strip()

 

 

5.  保存csv格式

from pandas import DataFrame

shop_dict = {'品牌名':pinpai_list, '店铺名': shop_list, '店铺链接': url_list}

   print('-----', shop_dict)

   data = DataFrame(shop_dict)

   data.to_csv('tianmao000001.csv', header=True, index=None,encoding='utf-8')

6.年月日

import datetime

 

def dateRange(start, end, step=1,format="%Y-%m-%d"):

   strptime, strftime = datetime.datetime.strptime, datetime.datetime.strftime

   days = (strptime(end, format) - strptime(start, format)).days

   d_list = [strftime(strptime(start, format) + datetime.timedelta(i),format) for i in range(0, days, step)]

   day_list = []

   for j in range(len(d_list)):

       day_list.append(d_list[j].replace('-', ''))

   return day_list

 

if __name__ == '__main__':

print(dateRange("2017-05-01", "2018-01-01"))

6.5  时间转换

对于时间数据,如2016-05-05 20:28:54,有时需要与时间戳进行相互的运算,此时就需要对两种形式进行转换,在Python中,转换时需要用到time模块,具体的操作有如下的几种:

  • 将时间转换为时间戳
  • 重新格式化时间
  • 时间戳转换为时间
  • 获取当前时间及将其转换成时间戳

1、将时间转换成时间戳

将如上的时间2016-05-05 20:28:54转换成时间戳,具体的操作过程为:

  • 利用strptime()函数将时间转换成时间数组
  • 利用mktime()函数将时间数组转换成时间戳

#coding:UTF-8

import time

 

dt = "2016-05-05 20:28:54"

 

#转换成时间数组

timeArray = time.strptime(dt, "%Y-%m-%d%H:%M:%S")

#转换成时间戳

timestamp = time.mktime(timeArray)

 

print timestamp

·        1

·        2

·        3

·        4

·        5

·        6

·        7

·        8

·        9

·        10

·        11

2、重新格式化时间

重新格式化时间需要以下的两个步骤:

  • 利用strptime()函数将时间转换成时间数组
  • 利用strftime()函数重新格式化时间

#coding:UTF-8

import time

 

dt = "2016-05-05 20:28:54"

 

#转换成时间数组

timeArray = time.strptime(dt, "%Y-%m-%d%H:%M:%S")

#转换成新的时间格式(20160505-20:28:54)

dt_new = time.strftime("%Y%m%d-%H:%M:%S",timeArray)

 

print dt_new

·        1

·        2

·        3

·        4

·        5

·        6

·        7

·        8

·        9

·        10

·        11

·        12

3、将时间戳转换成时间

在时间戳转换成时间中,首先需要将时间戳转换成localtime,再转换成时间的具体格式:

  • 利用localtime()函数将时间戳转化成localtime的格式
  • 利用strftime()函数重新格式化时间

#coding:UTF-8

import time

 

timestamp = 1462451334

 

#转换成localtime

time_local = time.localtime(timestamp)

#转换成新的时间格式(2016-05-05 20:28:54)

dt = time.strftime("%Y-%m-%d%H:%M:%S",time_local)

 

print dt

·        1

·        2

·        3

·        4

·        5

·        6

·        7

·        8

·        9

·        10

·        11

·        12

4、按指定的格式获取当前时间

利用time()获取当前时间,再利用localtime()函数转换为localtime,最后利用strftime()函数重新格式化时间。

#coding:UTF-8

import time

 

#获取当前时间

time_now = int(time.time())

#转换成localtime

time_local = time.localtime(time_now)

#转换成新的时间格式(2016-05-09 18:59:20)

dt = time.strftime("%Y-%m-%d%H:%M:%S",time_local)

print dt

 

5 指定日期三天前的 日期

def get_day_nday_ago(self, date, i):
   
# 获取指定日期前3天的日期
    # print(date)
   
t = time.strptime(date, "%Y-%m-%d")
   
y, m, d = t[0:3]
   
Date = str(datetime.datetime(y, m, d) - datetime.timedelta(i)).split()
   
return Date[0]

def day_num(self, day):
   
# days = ['2018-03-18', '2018-03-19','2018-03-20', '2018-03-21', '2018-03-22', '2018-03-23', '2018-03-24','2018-03-25', '2018-03-26', '2018-03-27', '2018-03-28', '2018-03-29','2018-03-30',  '2018-03-31','2018-04-01','2018-04-02', '2018-04-03', '2018-04-04', '2018-04-05', '2018-04-06','2018-04-07', '2018-04-08', '2018-04-09', '2018-04-10', '2018-04-11','2018-04-12', '2018-04-13', '2018-04-14', '2018-04-15', '2018-04-16']
    # print(day)
   
a = datetime.datetime.now()
   
b = a.strftime('%Y%m%d')
   
day02 = b[0:4] + '-' + b[4:6] + '-' + b[6:8]
   
days_list = []
    for i in range(1, 31):
       
a = self.get_day_nday_ago(day02, i)
       
days_list.append(a)
    days = days_list[::-1]

 6.--------------------------

在python的datetime模块中没有一个月有多少天的方法,但是可以使用calendar模块获得。
 
如下代码:
import calendar
monthRange = calendar.monthrange(2013,6)
print monthRange
 
输出:
(530)
 
输出的是一个元组,第一个元素是上一个月的最后一天为星期几(0-6),星期天为0;第二个元素是这个月的天数。

其他回答

1
2
3
4
5
 import calendar
print calendar.monthrange(2015,4)
 
#输出一个元组,第一个数字2代表这个月第一天是星期3,第二个数字30代表这个月有30天 
(230)

所有日期、时间的api都在datetime模块内。

1.日期输出格式化datetime => string

importdatetime

now= datetime.datetime.now()

now.strftime('%Y-%m-%d%H:%M:%S')  

输出

'2015-04-07 19:11:21'

strftimedatetime类的实例方法。

 

2.日期输出格式化string => datetime

importdatetime

t_str= '2015-04-07 19:11:21'

d= datetime.datetime.strptime(t_str, '%Y-%m-%d %H:%M:%S')

strptimedatetime类的静态方法。

 

3.日期比较操作

datetime模块中有timedelta类,这个类的对象用于表示一个时间间隔,比如两个日期或者时间的差别。

构造方法:

importdatetime

datetime.timedelta(days=0,seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)  

所有的参数都有默认值0,这些参数可以是intfloat,正的或负的。

可以通过timedelta.daystiemdelta.seconds等获取相应的时间值。

timedelta 类的实例,支持加、减、乘、除等操作,所得的结果也是timedelta 类的实例。比如:

importdatetime

year= datetime.timedelta(days=365)

ten_years= year *10

nine_years= ten_years - year  

同时,datetimedatetime类也支持与timedelta的加、减运算。

datetime1= datetime2 + timedelta

timedelta= datetime1 - datetime2

这样,可以很方便的实现一些功能。

 

4.两个日期相差多少天。

importdatetime

d1= datetime.datetime.strptime('2015-03-05 17:41:20', '%Y-%m-%d %H:%M:%S')

d2= datetime.datetime.strptime('2015-03-02 17:41:20', '%Y-%m-%d %H:%M:%S')

delta= d1 - d2

printdelta.days  

输出:3

 

5.今天的n天后的日期。

importdatetime

now= datetime.datetime.now()

delta= datetime.timedelta(days=3)

n_days= now + delta

printn_days.strftime('%Y-%m-%d %H:%M:%S')  

输出:

2015-04-10 19:16:34

 

#coding=utf-8

importdatetime

now=datetime.datetime.now()

printnow

 

#将日期转化为字符串

datetime=> string

importdatetime

now=datetime.datetime.now()

printnow.strftime('%Y-%m-%d %H:%M:%S')

 

#将字符串转换为日期 string=> datetime

importdatetime

t_str= '2015-03-05 16:26:23'

d=datetime.datetime.strptime(t_str,'%Y-%m-%d%H:%M:%S')

printd

#datetime模块中有timedelta类,这个类的对象用于表示一个时间间隔,比如两个日#期或者时间的差别。

 

#计算两个日期的间隔

importdatetime

d1= datetime.datetime.strptime('2012-03-05 17:41:20', '%Y-%m-%d %H:%M:%S')

d2= datetime.datetime.strptime('2012-03-02 17:41:20', '%Y-%m-%d %H:%M:%S')

delta= d1 - d2

printdelta.days print delta

 

#今天的n天后的日期

importdatetime

now=datetime.datetime.now()

delta=datetime.timedelta(days=3)

n_days=now+delta

printn_days.strftime('%Y-%m-%d %H:%M:%S')

 

import time
time.strftime('%Y%m%d')
//
获取了当前时间的年月日

 

datetime

获取昨天的时间

import datetime
now_time = date time.datetime.now()
yes_time = now_time + date time.timedelta(days=-1)
yes_time_nyr = yes_time.strftime('%Y%m%d')//
格式化输出

python求一个时间点的前一个月和后一个月

原创 2017年07月20日 18:35:32

·        标签:

·        python /

·        时间函数 /

·        前一个月 /

·        后一个月

·        4483

python如何获取一个时间点的前一个月和后一个月,网上虽然有很多教程,但是本人感觉太杂了而且不太好用,研究一番之后决定提供一种方法和思路。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import calendar
 
time = datetime.date(2017, 7, 20) #年,月,日
 
#求该月第一天
first_day = datetime.date(time.year, time.month, 1)
printu'该月第一天:' + str(first_day)
 
#前一个月最后一天
pre_month = first_day - datetime.timedelta(days = 1) #timedelta是一个不错的函数
printu'前一个月最后一天:' + str(pre_month)
#前一个月的第一天
first_day_of_pre_month = datetime.date(pre_month.year, pre_month.month, 1)
printu'前一个月的第一天:' + str(first_day_of_pre_month)
 
#求后一个月的第一天
days_num = calendar.monthrange(first_day.year, first_day.month)[1] #获取一个月有多少天
first_day_of_next_month = first_day + datetime.timedelta(days = days_num) #当月的最后一天只需要days_num-1即可
printu'后一个月的第一天:' + str(first_day_of_next_month)
·         1
运行结果如下 
                              
 

python获取日期加减之后的日期

python语言中的datetime模块可以利用其中的方法获取不同的日期,比如获取当前日期、明天、昨天、上个月、下个月和明年。下面利用几个实例说明这些日期的获取方法,操作如下:

 

ssssss

 



 

》》》>>>>>>>>>>>: pandas,numpy

1.  读取csv文件   转化结果

import pandas as pd
import numpy as np
'''
csv  文件内容
goods,shop
1,1
2,2
3,3
'''
b = '10010'
data = pd.read_csv('gggggg.csv')
for i in range(len(data)):
    goods = data['goods'][i]
    print(goods)
    print(type(goods))
    print(goods.item())
    print(type(goods.item()))
    print(np.array(list(b)).tostring())
    print('\n\n')
'''
8
<class 'numpy.int64'>
8
<class 'int'>
b'1\x00\x00\x000\x00\x00\x000\x00\x00\x001\x00\x00\x000\x00\x00\x00'

'''

 

 

 


posted @ 2018-04-28 09:46  殇夜00  阅读(10)  评论(0)    收藏  举报