Python - 从Datetime字符串中删除时间

pyt*_*ter 32 python datetime strptime python-2.7

我有一个日期字符串,并希望将其转换为日期类型:

我试图使用datetime.datetime.strptime和我想要的格式,但它返回转换的时间.

    when = alldates[int(daypos[0])]
    print when, type(when)

    then = datetime.datetime.strptime(when, '%Y-%m-%d')
    print then, type(then)
Run Code Online (Sandbox Code Playgroud)

这是输出返回的内容:

   2013-05-07 <type 'str'>
   2013-05-07 00:00:00 <type 'datetime.datetime'>
Run Code Online (Sandbox Code Playgroud)

我需要删除时间:00:00:00.

Woo*_*ide 54

print then.date()
Run Code Online (Sandbox Code Playgroud)

你想要的是一个datetime.date对象.你拥有的是datetime.datetime对象.您可以按照上面的方式更改对象,也可以在创建对象时执行以下操作:

then = datetime.datetime.strptime(when, '%Y-%m-%d').date()
Run Code Online (Sandbox Code Playgroud)


Ign*_*ams 5

>>> print then.date(), type(then.date())
2013-05-07 <type 'datetime.date'>
Run Code Online (Sandbox Code Playgroud)


ukr*_*utt 5

如果您需要时区感知结果,您可以使用对象的replace()方法datetime。这会保留时区,所以你可以这样做

>>> from django.utils import timezone
>>> now = timezone.now()
>>> now
datetime.datetime(2018, 8, 30, 14, 15, 43, 726252, tzinfo=<UTC>)
>>> now.replace(hour=0, minute=0, second=0, microsecond=0)
datetime.datetime(2018, 8, 30, 0, 0, tzinfo=<UTC>)
Run Code Online (Sandbox Code Playgroud)

请注意,这将返回一个新的日期时间对象——now保持不变。