Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
时间元组的日期字符串(python)_Python_Datetime - Fatal编程技术网

时间元组的日期字符串(python)

时间元组的日期字符串(python),python,datetime,Python,Datetime,这是我的问题: 我正在尝试将字符串传递到as函数,并需要将其转换为时间元组: def sim(startdate, enddate): #need to convert the date from string to integer time tuple: dt_start = dt.date(startdate) print 'Start Date: ', dt_start dt_end = dt.date(enddate) pri

这是我的问题:

我正在尝试将字符串传递到as函数,并需要将其转换为时间元组:

  def  sim(startdate, enddate):
     #need to convert the date from string to integer time tuple:


     dt_start = dt.date(startdate)
     print 'Start Date: ', dt_start

     dt_end = dt.date(enddate)
     print 'End Date: ', dt_end

 # in String format
 sim('Jan 1, 2011', 'Dec 31, 2011')

 # in interger in string format
 sim('2011,1,1', '2011,12,31')

您可能正在尝试执行以下操作:

import datetime as dt

year,month,day = map(int, '2011,1,1'.split(','))
dt_start = dt.date(year,month,day)
print dt_start # prints 2011-01-01

错误是因为使用了字符串
'2011,1,1'
而不是整数:
2011,1,1
作为输入:
datetime.date()。为这两种格式定义时间格式,并相应地使用它们。这就是我的意思:

import datetime as dt

def  sim(startdate, enddate):
    time_format_one = "%b %d, %Y"
    time_format_two = "%Y,%m,%d"

    try:
        dt_start = dt.datetime.strptime(startdate, time_format_one)
        dt_end = dt.datetime.strptime(enddate, time_format_one)
    except ValueError:
        dt_start = dt.datetime.strptime(startdate, time_format_two)
        dt_end = dt.datetime.strptime(enddate, time_format_two)

    print 'Start Date: ', dt_start.date()
    print 'End Date: ', dt_end.date()

# in String format
sim('Jan 1, 2011', 'Dec 31, 2011')

# in interger in string format
sim('2011,1,1', '2011,12,31')
印刷品:

Start Date:  2011-01-01
End Date:  2011-12-31
Start Date:  2011-01-01
End Date:  2011-12-31

如果需要时间元组,您可以使用on
dt_start
dt_end

我假设您希望将日期('2011年1月1日'、'2011年12月31日')和('2011,1,1'、'2011,12,31')转换为时间元组

 from datetime import datetime
 date_str = "Jan 1, 2011"
 fmt = "%b %d, %Y"

 # Construct a datetime object
 date_obj = datetime.strptime(date_str, fmt)

 # Convert it to any string format you want
 new_fmt = "%Y, %m, %d"
 print date_obj.strftime(new_fmt)
 # Prints'2011, 01, 01'

 # If you want python timetuple then
 t_tuple = date_obj.timetuple()

你能解释一下整数时间元组是什么意思吗?包含预期的输出将有助于DT.date(2011,1,1)如果不是2011,1,1格式,则会抛出错误,因此需要以某种方式进行转换。为什么不使用?导入datetime作为dt@pythonhunter当然-可以传递int而不是字符串,否则必须解析它。你有什么别的想法?