将给定日期以来的日期时间转换为分钟 [英] Convert datetime since a given date to minutes
问题描述
可能重复:
Python日期时间到Unix时间戳
Possible Duplicate:
Python datetime to Unix timestamp
是否有一种方法可以将datetime
转换为int
(代表自2012年1月以来的分钟数),以便可以修改此int
,将其写入数据库,进行比较等等?
我在其上运行的服务器使用Python 2.6.6
Is there a way to convert a datetime
to int
, representing the minutes since, for example, January 2012, so that this int
can be modified, written to a database, compared and so on?
The server I am running this on uses Python 2.6.6
推荐答案
减去两个datetime.datetime
对象将为您提供 timedelta
对象,其中具有 .total_seconds()
方法(已在Python 2.7中添加).将其除以60,然后转换为int()
,以获取自您的参考日期以来的分钟数:
Subtracting two datetime.datetime
objects gives you a timedelta
object, which has a .total_seconds()
method (added in Python 2.7). Divide this by 60 and cast to int()
to get minutes since your reference date:
import datetime
january1st = datetime.datetime(2012, 01, 01)
timesince = datetime.datetime.now() - january1st
minutessince = int(timesince.total_seconds() / 60)
或在python shell中:
or in a python shell:
>>> import datetime
>>> january1st = datetime.datetime(2012, 01, 01)
>>> timesince = datetime.datetime.now() - january1st
>>> minutessince = int(timesince.total_seconds() / 60)
>>> minutessince
346208
对于python 2.6及更早版本,您必须使用.days
和.seconds
属性来计算分钟数:
For python 2.6 and earlier, you'll have to use the .days
and .seconds
attributes to calculate the minutes:
minutessince = timesince.days * 1440 + timesince.seconds // 60
这也为您提供了一个整数.
which gives you an integer as well.
这篇关于将给定日期以来的日期时间转换为分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!