我已将offset_str
转换为offset_str = '01:00:00'
的时间,如下所示:
offset_time = datetime.strptime(offset_str, '%H:%M:%S').time()
offset_delta = timedelta(hours=offset_time.hour)
如何将offset_str = "-1 day, 18:00:00"
转换为时间?
我已经尝试过以下命令,但它没有用。
offset_str_list = offset_str.split(',')
offset_time_h = dt.datetime.strptime(offset_str_list[1].replace(" ", ""), '%H:%M:%S').time()
delta = dt.timedelta(hours = -23)
offset_time = ((dt.datetime.combine(dt.date(1,1,1),offset_time_h) + delta).time())
答案 0 :(得分:0)
不确定这是你所追求的,但是它的价值是什么:
import datetime
offset_str = "-1 day, 18:00:00"
# break up string
off_amt,off_time = offset_str.split(',')
off_time = off_time.strip()
time_val,time_increment = off_amt.split(' ')
# Get today's date YYYY-MM-DD
now = datetime.datetime.today()
now_ymd = datetime.datetime.strftime(now,'%Y-%m-%d')
#Create date and time string, convert to a datetime object
now_ymd = now_ymd + ' ' + off_time
use_date = datetime.datetime.strptime(now_ymd, "%Y-%m-%d %H:%M:%S")
#Calculate new date
new_date = use_date+datetime.timedelta(days=int(time_val))
print "old date ", use_date
print "new date ", new_date
输出:
old date 2016-01-15 18:00:00
new date 2016-01-14 18:00:00
答案 1 :(得分:-1)
您可以使用Arrow。这是快速入门的第一个例子。 例如,从现在开始具有前一小时的日期:
>>> import arrow
>>> utc = arrow.utcnow()
>>> utc.replace(hours=-1)
<Arrow [2016-01-15T14:36:12.820122+00:00]>
>>> str(utc.replace(hours=-1))
'2016-01-15T14:36:12.820122+00:00'
>>> str(utc.replace(days=-1))
'2016-01-14T14:36:12.820122+00:00'
>>> utc.replace(hours=-1).strftime("%Y-%m-%d %H:%M:%S")
'2016-01-15 14:36:12'