Python获取当前时间前、后一个月的函数

Python057

Python获取当前时间前、后一个月的函数,第1张

这需求折腾了我半天..

import time

import datetime as datetime

def late_time(time2):

    # 先获得时间数组格式的日期

    #time2是外部传入的任意日期

    now_time = datetime.datetime.strptime(time2, '%Y-%m-%d')

  #如需求是当前时间则去掉函数参数改写      为datetime.datetime.now()

    threeDayAgo = (now_time - datetime.timedelta(days =30))

    # 转换为时间戳

    timeStamp =int(time.mktime(threeDayAgo.timetuple()))

    # 转换为其他字符串格式

    otherStyleTime = threeDayAgo.strftime("%Y-%m-%d")

    return otherStyleTime

a = late_time("2019-3-30")

print(a)# 打印2018-02-28

python中datetime设置时区步骤如下:

1、点击键盘 win+r,打开运行窗口;在窗口中输入“cmd",点击确定,打开windows命令行窗口。

2、在cmd命令行窗口中输入"python",进入python交互窗口。

3、导入datetime模块。

4、通过datetime.datetime.now()函数,获取当前时间。

5、使用datetime.datetime()函数,设置时间,并打印出来。

6、可以分别将设置时间的年、月、日、时、分、秒打印。