将日期时间对象转换为整数python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29238540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting a datetime object to an integer python
提问by user4690602
I would like to convert a datetime object to an int in python:
我想在 python 中将 datetime 对象转换为 int:
import datetime
time_entered = datetime.datetime.strptime(raw_input("Time1: "), "%H%M")
time_left = datetime.datetime.strptime(raw_input("Time2"), "%H%M")
time_taken = time_left - time_entered
int(time_taken)
When I run that code I get the following error:
当我运行该代码时,出现以下错误:
TypeError: int() argument must be a string or a number, not 'datetime.timedelta'
类型错误:int() 参数必须是字符串或数字,而不是“datetime.timedelta”
回答by Molek
You can convert the datetime object to a timetuple, and then use the time.mktime function
您可以将日期时间对象转换为时间元组,然后使用 time.mktime 函数
import time
from datetime import datetime
timestamp = int(time.mktime(datetime.now().timetuple()))
Convert it back with:
将其转换回:
now = datetime.fromtimestamp(timestamp)