在python中str到时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4183793/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:40:21  来源:igfitidea点击:

str to time in python

pythondatetimestrptime

提问by Rajeev

time1 = "2010-04-20 10:07:30"
time2 = "2010-04-21 10:07:30"

How to convert the above from string to time stamp?

如何将上述内容从字符串转换为时间戳?

I need to subtract the above timestamps time2-time1.

我需要减去上面的时间戳time2-time1

采纳答案by knitti

For Python 2.5+

对于 Python 2.5+

from datetime import datetime
format = '%Y-%m-%d %H:%M:%S'
print datetime.strptime(time2, format) - 
        datetime.strptime(time1, format)
# 1 day, 0:00:00

Edit:for Python 2.4

编辑:对于 Python 2.4

import time
format = '%Y-%m-%d %H:%M:%S'
print time.mktime(time.strptime(time2, format)) - 
        time.mktime(time.strptime(time1, format))
# 86400.0

回答by mouad

import time

time1 = "2010-04-20 10:07:30"

time_tuple = time.strptime(time1, "%Y-%m-%d %H:%M:%S")

timestamp = time.mktime(time_tuple)

回答by John La Rooy

>>> t1 = datetime.strptime(time1, "%Y-%m-%d %H:%M:%S")
>>> t2 = datetime.strptime(time2, "%Y-%m-%d %H:%M:%S")
>>> t2-t1
datetime.timedelta(1)

>>> (t2-t1).days
1
>>> (t2-t1).seconds
0

回答by rubayeet

If you're stuck on Python 2.4 system like me:

如果你像我一样被困在 Python 2.4 系统上:

from time import strptime
from datetime import datetime

str_to_datetime = lambda st: datetime(*strptime(st, '%Y-%m-%d %H:%M:%S')[:6])

str_to_datetime('2010-04-20 10:07:30')

Otherwise datetime.strptime() will work just fine.

否则 datetime.strptime() 会正常工作。