将给定日期以来的日期时间转换为分钟 [英] Convert datetime since a given date to minutes

查看:183
本文介绍了将给定日期以来的日期时间转换为分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
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对象,其中具有

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆