9月 10

python格式化n天前日期

需要获取n天前,或者n天后的信息。比如获取一天前,格式化为2015-10-09的格式。

导入time,time.time()为unixtime,60*60*24就是60秒乘60分钟乘24小时,减去一天就是一天前,加上一天就是后一天。

import time
time.strftime("%Y-%m-%d", time.localtime(time.time()-60*60*24))

可以自己计算n年,n月,n小时,n秒。

8月 11

python 中 json读写

import json

# 读取json文件
def read_json(file_name):
    json_file = open("%s" % file_name, "rb")
    get_json = json.load(json_file)
    json_file.close()
    return get_json

# 写入json文件
def write_json(file_name, json_context):
    json_file = open("%s" % file_name, "wb")
    to_json = json.dumps(json_context)
    json_file.write(to_json)
    json_file.close()