0

I want to remove special character '-' from date format in 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'

I have tried in different ways but could not get proper answer. How can I get in a simple way? Thanks for your time.

mitco
  • 35
  • 7

2 Answers2

0

just rebuild a new dictionary using dict comprehension, iterating on the original dictionary, and stripping the unwanted characters from values using 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:

s = {v.replace("-","") for _,v in d.items()}
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • hello jean it works perfectly but i just want single value '20170221'. Do you have any idea how can I select a value from a key or index of value ? – mitco Mar 06 '17 at 10:34
  • you mean you need uniqueness of values and drop the keys? – Jean-François Fabre Mar 06 '17 at 10:36
  • ya, sort of because when I retrive a max date it gives me two values with two keys. '0' and '_c0' with same date. So, want single value '20170221' without key. – mitco Mar 06 '17 at 10:41
  • I made the changes as you suggested but why it gives me `set(['20170221'])` instead '20170221' ? – mitco Mar 06 '17 at 10:49
  • @ Jean thanks a lot for your help. I got it now. ` r = {v.replace("-","") for _,v in value.items()}` gives `set(['20170221'])` further, `s = ''.join(x for x in r if x.isdigit())` and `int(s)` gives me desired output `20170221`. – mitco Mar 06 '17 at 12:35
0

You can try 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

Community
  • 1
  • 1
KimKulling
  • 2,654
  • 1
  • 15
  • 26