时间: 2020-08-30|tag:52次围观|0 条评论

今天有朋友在群里问到,网页上那种“XX分钟前发表”,这种时间怎么用 Python实现。

原理上来说,发表的时候打一个时间戳,阅读的时候再打一个时间戳。具体实现就是使用 Python 的两个自带的标准库 datetime 和 time。先用两种方法快速实现如何得到两个时间戳,以及如何计算两个时刻的时间间隔。

1 datetime 计算时间差

datetime.datetime.now() 拿到时间戳,两个时间戳相减,再用 datetime 对象的 .seconds 属性得到两个时间戳之间的秒数。

>>> import datetime>>> start = datetime.datetime.now()>>> end = datetime.datetime.now()>>> interval = end - start>>> interval.seconds130

2 time 计算时间差

time.time() 得到时间戳秒数,两个秒数相减,直接就是时间秒数。

>>> import time>>> begin = time.time()>>> finish = time.time()>>> duration = int(finish) - int(begin)>>> duration349

3 datetime 与 time 的一些细节

3.1 时间差是什么对象,有何区别

对于上面计算出来的两种 intervalduration

两个 datetime.datetime 对象相减,得到的是 datetime.timedelta 对象。而 datetime.timedelta 对象有两个属性:.seconds.days,可以分别查看对应的"秒"和"日"。

比如,查看两个时间戳之间的秒级别的差别。可以用 .seconds

>>> sec_1 = datetime.datetime(2017, 8, 10, 0, 0, 0, 000000)>>> sec_2 = datetime.datetime(2017, 8, 10, 0, 0, 30, 000000)>>> interval_sec = sec_2 - sec_1>>> interval_secdatetime.timedelta(0, 30)>>> interval_sec.seconds30

查看天级别的差别,用 .days

>>> day_1 = datetime.datetime(2017, 8, 1, 0, 0, 0, 000000)>>> day_2 = datetime.datetime(2017, 8, 16, 0, 0, 0, 000000)>>> interval_day = day_2 - day_1>>> interval_daydatetime.timedelta(15)>>> interval_day.days15

3.2 为什么 time.time() 计算时间差要用 int() 先转换

在上面的例子中,我们使用了 int() 先把 time.time() 得到的浮点数,转换成整型以后再计算。

>>> duration = int(finish) - int(begin)>>> duration349

因为 Python 的浮点运算是不可靠的,当然用 Decimal 库另说。

>>> a = 1>>> b = float(a)>>> b == 1.00000000000000000000001True>>> 0.1+0.1+0.1 == 0.3False

参照 Python 浮点数运算

3.3 日期、时间与字符串的转换

参照

PYTHON-基础-时间日期处理小结

这里转换以后会用到 MySQL 的 insert 语句中。

str() 可以得到 '2017-08-18 00:00:00'

>>> import datetime>>> d = datetime.datetime(2017,8,18)>>> ddatetime.datetime(2017, 8, 18, 0, 0)>>> str(d)'2017-08-18 00:00:00'

这样就可以插入 Datetime 类型的 MySQL 字段中。比如 MySQL 中有一个字段是 stat_time,这里可以把 d = '2017-08-18 00:00:00' 格式的内容插入到 MySQL 表中。

def insert_to_tbl(d):    """ 插入表 """    con = MySQLdb.connect(HOSTNAME, USERNAME, PASSWORD, DATABASE)    con.set_character_set('utf8')    with con as cur:        cur.execute('SET NAMES utf8;')        sql_str = "insert into some_database.some_tbl (stat_time) values ('{}')"        sql = sql_str.format(d)        cur.execute(sql)

如果需要 YYYY-MM-DD 格式的日期,可以把 date 对象用 isoformat() 进行转换。

>>> import datetime>>> d = datetime.datetime(2017,8,18)datetime.datetime(2017, 8, 18, 0, 0)# 得到 date 对象>>> d.date()datetime.date(2017, 8, 18)# date对象可以转成 isoformat 格式>>> d.date().isoformat()'2017-08-18'>>> d1 = d.date().isoformat()>>> d1'2017-08-18'>>> type(d1)<type 'str'>

当然 datetime 对象也可以进行 isoformat() 转换。而这种格式也是可以直接插入到 MySQL 中的。

>>> d.isoformat()'2017-08-18T00:00:00'

关于 Python 用 MySQLdb 插入时间、日期对象的参考:

最热门的回答Inserting a Python datetime.datetime object into MySQL

参考答案:

这里之所以可以直接把 now 这个 datetime 对象进行插入,是因为 %s 占位符自动进行了 str() 转换。

now = datetime.datetime(2009, 5, 5)cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s, '%s')", ("name", 4, now))

Select DateTime mysql query in python

Inserting datetime into MySql db

文章转载于:https://www.jianshu.com/p/309fcf2f316a

原著是一个有趣的人,若有侵权,请通知删除

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《Python 对于时间的处理
   

还没有人抢沙发呢~