我试图使用strptime将日期和时间转换为DateTime字段。也就是说,将输入转换为"星期五下午3:00和#34;到日期时间字段。这是一个连续三天发生的事件,所以我知道星期五将是二月的特定日,依此类推。
我的问题是,我该如何做呢?如何将周五下午3:00转换为2017-02-24 15:00:00?
我现在在我的Django项目中,在views.py中是:
new_request.start = time.strptime(form.cleaned_data['start'], '%A %I:%M %p')
然后,我必须打印"星期五下午3点"从datetime字段后来,使用strftime,我假设是与上面的相反?
谢谢!
答案 0 :(得分:0)
您可以调整以下示例以实现您想要的目标:
import time
time.strftime("%Y-%d-%m %H:%M:%S", time.strptime('Friday 3 February 2017 3:00PM', '%A %d %B %Y %I:%M%p'))
# Output: '2017-03-02 15:00:00'
如果年份和月份固定为2017年和2月,就像您提到的那样"周五下午3:00"可以转换如下:
time.strftime("2017-%d-2 %H:%M:%S", time.strptime('Friday 3 3:00PM', '%A %d %I:%M%p'))
# Output: '2017-03-2 15:00:00'
如果您想获取datetime
对象,请使用以下内容:
from datetime import datetime
datetime.strptime('Friday 3 February 2017 3:00PM', '%A %d %B %Y %I:%M%p')
# Output: datetime.datetime(2017, 2, 3, 15, 0)
答案 1 :(得分:0)
您可以使用python-dateutil将可读时间字符串解析为datetime对象。它非常方便易用。
其文档页面中的示例:
>>> from dateutil.relativedelta import *
>>> from dateutil.easter import *
>>> from dateutil.rrule import *
>>> from dateutil.parser import *
>>> from datetime import *
>>> now = parse("Sat Oct 11 17:13:46 UTC 2003")
>>> today = now.date()
>>> year = rrule(YEARLY,dtstart=now,bymonth=8,bymonthday=13,byweekday=FR)[0].year
>>> rdelta = relativedelta(easter(year), today)
>>> print("Today is: %s" % today)
Today is: 2003-10-11
>>> print("Year with next Aug 13th on a Friday is: %s" % year)
Year with next Aug 13th on a Friday is: 2004
>>> print("How far is the Easter of that year: %s" % rdelta)
How far is the Easter of that year: relativedelta(months=+6)
>>> print("And the Easter of that year is: %s" % (today+rdelta))
And the Easter of that year is: 2004-04-11