Python 获取时间的方法

1,078 阅读1分钟

方法一:

获取当前时间对象

from datetime import datetime, timedelta

now = datetime.now()

分别获取当前时间的年份、月份、和日子

year = now.year

month = now.month

day = now.day

print(now)

获取当前这个月1号的字符串

month_first_day_str = "%d-%02d-01" % (year, month)

print(month_first_day_str)

获取当前这个月1号的时间对象

"""/将字符串转为对象,这个对象就可以点出year,month,day/"""

month_first_day_date = datetime.strptime(month_first_day_str, "%Y-%m-%d")

print(month_first_day_date)

获取今天3点15分的时间对象

temp_str = ("%d-%02d-%02d 03:15:00" % (year, month, day))

temp_date = datetime.strptime(temp_str, "%Y-%m-%d %H:%M:%S") # 对象

print(temp_date)

获取前天3点15分的时间对象

temp_date2 = temp_date - timedelta(2)

print(temp_date2)

获取今天0点的时间对象

temp_str3 = ("%d-%02d-%02d" % (year, month, day))

temp_date3 = datetime.strptime(temp_str3, "%Y-%m-%d")

print(temp_date3)

获取昨天0点的时间对象

temp_str4 = ("%d-%02d-%02d" % (year, month, day))

temp_date4 = datetime.strptime(temp_str3, "%Y-%m-%d") - timedelta(1)

print(temp_date4)

方法二

获取当前时间对象

import time

t = time.localtime()

分别获取当前时间的年份、月份、和日子

year = t.tm_year

month = t.tm_mon

day = t.tm_mday

获取当前这个月1号的字符串

month_first_day_str = "%d-%02d-01" % (year, month)

获取当前这个月1号的时间对象

"""/将字符串转为对象,这个对象就可以点出year,month,day/"""

month_first_day_date = datetime.strptime(month_first_day_str, "%Y-%m-%d")

获取今天3点15分的时间对象

temp_str = ("%d-%02d-%02d 03:15:00" % (year, month, day))

temp_date = datetime.strptime(temp_str, "%Y-%m-%d %H:%M:%S") # 对象

获取前天3点15分的时间对象

temp_date2 = temp_date - timedelta(2)

获取今天0点的时间对象

temp_str3 = ("%d-%02d-%02d" % (year, month, day))

temp_date3 = datetime.strptime(temp_str3, "%Y-%m-%d")

获取昨天0点的时间对象

temp_str4 = ("%d-%02d-%02d" % (year, month, day))

temp_date4 = datetime.strptime(temp_str3, "%Y-%m-%d") - timedelta(1)