首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Python如何获取昨天,今天,明天的日期字符串

在做一个爬虫需求的时候,需要同时爬取昨天,今天,明天的足球赛事数据,那么,在Python中,如何获取这三个特殊日期的字符串呢?

特意写下此博客,作为记录,也作为经验分享给大家。

首先是如何获取今天的日期字符串,这个之前的一篇文章中有提到过:

import time

def now_str():

# 获得当前时间时间戳

now = int(time.time())

# 转换为其他日期格式,如:"%Y-%m-%d %H:%M:%S"

time_obj = time.localtime(now)

return time.strftime("%Y-%m-%d", time_obj)

print(now_str())

如果要获取昨天的日期字符串,实际上将今天的时间减去一天的时间,再重新生成字符串就可以了,所以可以编写如下代码:

import time

def get_timestamp_str(seconds):

"""将时间秒之转换为日期字符串"""

return time.strftime("%Y-%m-%d", time.localtime(seconds))

def today():

"""获取今天的日期字符串"""

return get_timestamp_str(time.time())

def yesterday():

"""获取昨天的日期字符串"""

return get_timestamp_str(time.time() - 60 * 60 * 24 * 1)

print(yesterday())

print(today())

这里的60表示60秒钟,就是1分钟,60表示60分钟,就是1个小时,再24表示24小时,也就是1天的时间。当前时间减去一天的时间,就是昨天。

那么,要获取明天的时间就简单了,我们只需要加上一天就可以了,写法如下:

import time

def get_timestamp_str(seconds):

"""将时间秒之转换为日期字符串"""

return time.strftime("%Y-%m-%d", time.localtime(seconds))

def today():

"""获取今天的日期字符串"""

return get_timestamp_str(time.time())

def yesterday():

"""获取昨天的日期字符串"""

return get_timestamp_str(time.time() - 60 * 60 * 24 * 1)

def tomorrow():

"""获取明天的日期字符串"""

return get_timestamp_str(time.time() + 60 * 60 * 24 * 1)

print(yesterday())

print(today())

print(tomorrow())

  • 发表于:
  • 原文链接https://page.om.qq.com/page/O3E6OlcrzFPbUrBjW38QfTnw0
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券