Python中如何计算距离上次发帖已过多少天

这是我们一年前发过的帖子。 建了个 python 爱好者群。欢迎大家来互相交流。

截止目前,群里有一百人,我们是一群 Python 爱好者,有问题一起讨论。聚过线下,搞过项目,讨论技术,讨论感情(热爱 CP )现在我们希望有更多志同道合的朋友。

以下是我们的 CTO 为我们做的群成员分析。感兴趣的扫描二维码加入我们。

最后恭喜囧森圆梦 pm。


Python中如何计算距离上次发帖已过多少天

17 回复

🎉🎉🎉🎉🎉


from datetime import datetime, timezone
import pytz

def days_since_last_post(last_post_time_str, timezone_str='Asia/Shanghai'):
    """
    计算距离上次发帖已过多少天
    
    参数:
        last_post_time_str: 上次发帖时间字符串,格式为'YYYY-MM-DD HH:MM:SS'
        timezone_str: 时区字符串,默认为'Asia/Shanghai'
    
    返回:
        距离上次发帖的天数(整数)
    """
    # 设置时区
    tz = pytz.timezone(timezone_str)
    
    # 将字符串时间转换为datetime对象(带时区)
    last_post_time = datetime.strptime(last_post_time_str, '%Y-%m-%d %H:%M:%S')
    last_post_time = tz.localize(last_post_time)
    
    # 获取当前时间(带时区)
    current_time = datetime.now(tz)
    
    # 计算时间差
    time_difference = current_time - last_post_time
    
    # 返回天数
    return time_difference.days

# 使用示例
if __name__ == "__main__":
    # 假设上次发帖时间是2023-10-01 14:30:00
    last_post = "2023-10-01 14:30:00"
    
    days_passed = days_since_last_post(last_post)
    print(f"距离上次发帖已过去 {days_passed} 天")
    
    # 也可以指定其他时区
    days_passed_ny = days_since_last_post(last_post, 'America/New_York')
    print(f"纽约时区:距离上次发帖已过去 {days_passed_ny} 天")

这个实现用了datetimepytz库来处理时区问题,确保计算准确。pytz不是标准库,需要先安装:pip install pytz。函数返回的是完整的天数差,不考虑小时和分钟。

如果不想用第三方库,可以用Python 3.9+的zoneinfo

from datetime import datetime
from zoneinfo import ZoneInfo

def days_since_last_post_simple(last_post_time_str, timezone_str='Asia/Shanghai'):
    tz = ZoneInfo(timezone_str)
    last_post_time = datetime.strptime(last_post_time_str, '%Y-%m-%d %H:%M:%S').replace(tzinfo=tz)
    current_time = datetime.now(tz)
    return (current_time - last_post_time).days

datetime算时间差就行。

板凳前排围观

👏🏿👏🏿👏🏿转行一年感谢 py 群友们

一个群还能有 CTO ?

不过还真有点想进去,看看能不能吊到俩大汉帮我维护项目(滑稽

欢迎 小妹妹们~

exm ? 19 个女生?我怕是看见了个假群。🙊

不闹了,java 的静静看。
祝越来越好

本群第一人渣前来报道

这是可爱的小姐姐

就我一人好奇考试内容么

啥也不会能进?

小板凳 初入门爱好者~

可能是女装大佬……

不知道 git 猫为啥游章鱼的脚

章鱼猫呀, git 猫还没出生

章鱼猫背后有什么梗吗?

顶上去呀

回到顶部