【Python脚本】Python公众号

公众号:Python那些事

  • 日期生成

 

>>> range (1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range (1,10)[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
#形成reverse函数的效果
  •  获取过去10天的日期

#!/usr/bin/env python
#-*- encoding:utf-8 -*-
"""获取过去N天的日期"""
import datetime
def get_nday_list(n):
  before_n_days = []
  for i in range(1, n + 1)[::-1]:
    before_n_days.append(str(datetime.date.today() - datetime.timedelta(days=i)))
  return before_n_days
d = get_nday_list(10)
print(d)
['2022-03-28', '2022-03-29', '2022-03-30', '2022-03-31', '2022-04-01', '2022-04-02', '2022-04-03', '2022-04-04', '2022-04-05', '2022-04-06']
  • 生成一段时间区间内的日期

#!/usr/bin/env python
#-*- encoding:utf-8 -*-

import datetime
def create_assist_date(datestart = None, dateend = None):
  #创建日期辅助表
  if datestart is None:
    datestart = '202-04-07'
  if dateend is None:
    dateend =  datetime.datetime.now().strftime('%Y-%m-%d')
  #转为日期格式
  datestart = datetime.datetime.strptime(datestart,'%Y-%m-%d')
  dateend = datetime.datetime.strptime(dateend,'%Y-%m-%d')
  date_list = []
  date_list.append(datestart.strftime('%Y-%m-%d'))
  while datestart<dateend:
    #日期叠加一天
    datestart += datetime.timedelta(days =+ 1)
    #日期转字符串存入列表
    date_list.append(datestart.strftime('%Y-%m-%d'))
  return date_list
d_list = create_assist_date(datestart='2022-04-02', dateend='2022-04-07')
print(d_list)
['2022-04-02', '2022-04-03', '2022-04-04', '2022-04-05', '2022-04-06', '2022-04-07']
  •   保存数据到csv

#!/usr/bin/env python
#-*- encoding:utf-8 -*-
import os
def save_data(data, date):
  if not os.path.exists(r'2022_04_07_%s.csv' % date):
    with open("2022_04_07_%s.csv" % date, "a+", encoding='utf-8') as f:
      f.write("标题,热度,时间,url\n")
      for i in data:
        title = i["title"]
        extra = i["extra"]
        time = i['time']
        url = i["url"]
        row = '{},{},{},{}'.format(title,extra,time,url)
        f.write(row)
        f.write('\n')
  else:
    with open("2022_04_07_%s.csv" % data, "a+", encoding='utf-8') as f:
      for i in data:
        title = i["title"]
        extra = i["extra"]
        time = i["time"]
        url = i["utl"]
        row = '{},{},{},{}'.format(title, extra, time, url)
        f.write(row)
        f.write('\n')

  

  

 

posted on 2022-04-07 19:50  helontian  阅读(66)  评论(0)    收藏  举报