向当前数据时间增加+ 4小时

时间:2019-07-05 09:44:51

标签: python datetime orange

我有600个数组,数据格式为“ 2019-07-12 23:12:03”。我需要脚本,该脚本需要4个小时才能处理600个字符串。例如,“ 2019-07-12 23:12:03” +4小时-我们必须输入print()“ 2019-07-13 03:12:03”等。 这是Orange的file.plk中的数据集。一栏有这样的日期。我发现列是二维列表,日期是in_date [0] [0] ... in_date [600] [0]。那些是浮动的。因此,我可以+ 14400秒增加最多4个小时的时间,但是我需要像前面提到的那样以数据格式输出它。

5 个答案:

答案 0 :(得分:1)

您可以使用timedelta和列表映射:

from datetime import datetime, timedelta


def parse_plus_four_hours(datetime_str):
    return datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S') + timedelta(hours=4)


list_of_datetimes = ['2019-07-12 23:12:03', ...]
datetime_objects = list(map(parse_plus_four_hours, list_of_datetimes))

# datetime_objects contains all your datetime strings as real datetimes,
# plus 4 hours added

答案 1 :(得分:0)

  

Python strftime()

     

将日期,时间和日期时间对象转换为其等效的字符串

     

Python strptime()

     

从字符串创建日期时间对象

     

timedelta对象表示两个日期之间的差值,或者   时间。

from datetime import datetime, timedelta
#datetime.strptime is the main routine for parsing strings into datetimes. It can handle all sorts of formats

data_time =  "2019-07-12 23:12:03"
datetime_object = datetime.strptime(data_time, '%Y-%m-%d %H:%M:%S')

print ( datetime_object + timedelta(hours=4)) # <class 'datetime.datetime'>
print ((datetime_object + timedelta(hours=4)).strftime( '%Y-%m-%d %H:%M:%S'))# <class 'str'>

输出:

2019-07-13 03:12:03
2019-07-13 03:12:03

获取您的列表:

from datetime import datetime, timedelta

data_time =  ["2019-07-12 23:12:03", "2019-05-11 10:12:03", "2019-01-20 12:12:03"]
for item in data_time:
    datetime_object = datetime.strptime(item, '%Y-%m-%d %H:%M:%S')
    datetime_object = datetime_object + timedelta(hours=4)
    datetime_object_ = (datetime_object + timedelta(hours=4)).strftime( '%Y-%m-%d %H:%M:%S')
    print (datetime_object)
    print (datetime_object_)

答案 2 :(得分:0)

也许是这样的:

#!/usr/bin/python3
from datetime import datetime,timedelta
theList=['2019-07-12 23:12:03','2019-04-12 21:12:03','2019-07-18 23:11:03']
for item in theList:
    datetimeObject = datetime.strptime(item, '%Y-%m-%d %H:%M:%S')
    datetimeObject+= timedelta(hours=4)
    print(datetimeObject)

答案 3 :(得分:0)

from datetime import datetime, timedelta


currentHour = datetime.strptime('2019-07-12 23:12:03','%Y-%m-%d %H:%M:%S')
    hours_from_now = currentHours + timedelta(hours=4)

format(hours_from_now,'%Y-%m-%d %H:%M:%S')

答案 4 :(得分:0)

这可能会达到目的:

from datetime import datetime, timedelta

your_string = "2019-07-12 23:12:03"

datetime_obj = datetime.strptime(your_string, "%Y-%m-%d %H:%M:%S")

modded_time = datetime_obj + timedelta(hours=4)

print(modded_time)

它首先将您拥有的字符串转换为日期时间对象,然后nn将4小时加上usint timedelta

我从此示例得到的结果:

2019-07-13 03:12:03

现在,您迭代600个字符串并像这样处理它们-完成:)