简体   繁体   English

从python中的日期格式(整数)中删除特殊字符“-”

[英]remove special character '-' from date format (integer) in python

I want to remove special character '-' from date format in python. 我想从python中的日期格式中删除特殊字符“-”。 I have retrieved maximum date from a database column. 我已经从数据库列中检索了最大日期。 Here is my small code: 这是我的小代码:

def max_date():
    Max_Date= hive_select('SELECT  MAX (t_date) FROM ovisto.ovisto_log')
    value = Max_Date[0]
print value

Here is output: 输出如下:

{0: '2017-02-21', '_c0': '2017-02-21'}

I want only numbers without special character '-' from output. 我只希望输出中没有特殊字符“-”的数字。 so, I am expecting this answer '20170221' 所以,我希望这个答案是“ 20170221”

I have tried in different ways but could not get proper answer. 我以不同的方式尝试过,但无法获得正确的答案。 How can I get in a simple way? 我如何以简单的方式获得? Thanks for your time. 谢谢你的时间。

just rebuild a new dictionary using dict comprehension, iterating on the original dictionary, and stripping the unwanted characters from values using str.replace 只需使用dict理解来重建新词典,对原始词典进行迭代,并使用str.replace从值中str.replace不需要的字符

d = {0: '2017-02-21', '_c0': '2017-02-21'}

new_d = {k:v.replace("-","") for k,v in d.items()}

print(new_d)

result: 结果:

{0: '20170221', '_c0': '20170221'}

if you only want to keep the values and drop the duplicates (and the order too :), use a set comprehension with the values instead: 如果您只想保留这些值并删除重复项(以及顺序:),请对这些值使用set comprehension:

s = {v.replace("-","") for _,v in d.items()}

You can try strptime: 您可以尝试strptime:

value = Max_Date[0]
new_val= datetime.datetime.strptime( str( value ), '%Y%m%d').strftime('%m/%d/%y')

I found it here: How to convert a date string to different format 我在这里找到它: 如何将日期字符串转换为其他格式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM