2017-04-10 53 views
0

我有我应该忽略日期字符串中的时间戳的情况。我已经尝试了下面的命令,但没有运气。从Python中的日期字符串中删除时间戳

"start" variable used below is in AbsTime (Ex: 01MAY2017 11:45) and not a string. 

start_date = datetime.datetime.strptime(start, '%d%^b%Y').date() 
print start_date 

我的输出应该是:

01MAY2017 or 01MAY2017 00:00

可以在任何一个可以帮助我。

+1

'start.split() [0]'会给你第一个输出 –

+1

好奇:你从哪里得到'%^ b'的想法? –

+0

@MartijnPieters可能是一个错字。 '%'&'^'在常规键盘上的“5”和“6”(换档)上。 –

回答

5

你的指令略有偏差,你需要捕获所有的内容(不管你想保留什么)。

start_date = datetime.datetime.strptime(start, '%d%b%Y %H:%M').date() 
print start_date.strftime('%d%b%Y') 
# '01May2017' 

更新 - 添加下面的完整代码:

import datetime 
start = '01MAY2017 11:45' 
start_date = datetime.datetime.strptime(start, '%d%b%Y %H:%M').date() 
print start_date.strftime('%d%b%Y') 
# 01May2017 
+0

我已经尝试过,但得到以下错误:AttributeError:type object'datetime.datetime'has no attribute'datetime' – srisriv

+3

try'import datetime' '从日期时间导入日期时间' – shash678

+0

使用最新答案中的代码。你可能在解释器中导入了两次'datetime'。 –

0

https://docs.python.org/2/library/datetime.html

将字符串转换回日期时间,我们可以使用strptime使用strptime()

例( )

datetime.datetime.strptime('10Apr2017 00:00', '%d%b%Y %H:%M') 

In [17]: datetime.datetime.strptime('10Apr2017 00:00', '%d%b%Y %H:%M') 
Out[17]: datetime.datetime(2017, 4, 10, 0, 0) 

使用的strftime现在使用()返回,我们形成为一个字符串的DateTime对象,形成你的DateTime对象

datetime.datetime.now().strftime('%d%b%Y') 

In [14]: datetime.datetime.now().strftime('%d%b%Y') 
Out[14]: '10Apr2017' 
+1

OP只想保留一天。 –

+1

...而不是当天。 –

+0

这只是一个例子。重要部分strftime –

0

试试这个

import datetime 
    start = '01MAY2017 11:45' 
    start_date = datetime.datetime.strptime(start, '%d%b%Y %H:%M') 
    print start_date.strftime('%Y-%m-%d') 
相关问题