python(6)时间戳和北京时间互转,输出当前的时间和推到七天前的日期

时间:2022-10-20 05:46:19

项目发展的需要:(包含时间函数)time datetime

时间戳和北京时间互转

 import time
import datetime
s = '2015-04-17 11:25:30'
d = datetime.datetime.strptime(s,"%Y-%m-%d %H:%M:%S")
print int(time.mktime(d.timetuple()))

运行结果:1429241130

需要当前的日期,并显示出时间轴,然后推出七天前的具体日期

 #! /usr/bin/env python
# -*- coding=utf-8 -*-
import re
import time
from datetime import datetime
now = datetime.now()
list = [0,31,28,31,30,31,30,31,31,30,31,30,31]
def judge(year):#判断是否是闰年
if year % 100 == 0 and year % 400 == 0:
return 1
elif year % 100 != 0 and year % 4 == 0:
return 1
return 0 def GetNowTime():
#当前的时间
print "Now Time:"
print time.time()
print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
# 输出当前的:年月日 承接上面的 now = datetime.now()
# y = now.year
# m = now.month
# d = now.day
#输入年月日:
print "input:"
y = int (raw_input())
m = int (raw_input())
d = int (raw_input())
# print time.time()
# 输出年月日+具体的时间
# y = now.year
# m = now.month
# d = now.day
ymd = judge(y)
print "Input Time:"
print str(y)+"-"+str(m)+"-"+str(d)
#如果是闰年,则二月份 要加一
list[2] = list[2] + ymd
#时间倒退7天
if(d>7):
d = d-7
else:
#if it not is Janurary
if m!=1:
m = m-1
d = list[m]+d-7
#if it is Janurary
else:
y = y -1 #年份减去1
m = 12 #月份到12月
d = d+list[12]-7
#恢复二月的原始天数
print "eryue: " +str(list [2])
list[2] = list[2] - ymd
#输出七天七的日期
print 'Seven days ago:'
print str(y)+"-"+str(m)+"-"+str(d)
if __name__ == "__main__":
GetNowTime()

代码测试:

D:\Python27\python.exe D:/py/Bfun/donghua/test.py
Now Time:
1456717147.79
2016-02-29 11:39:07 input:
2015
03
07
Input Time:
2015-3-7
eryue: 28
Seven days ago:
2015-2-28
input:
2016
03
07
Input Time:
2016-3-7
eryue: 29
Seven days ago:
2016-2-29 input:
2016
01
07
Input Time:
2016-1-7
eryue: 29
Seven days ago:
2015-12-31