Home > Net >  Python Datetime: How do I get a date's FORMAT?
Python Datetime: How do I get a date's FORMAT?

Time:09-30

Basically, I need to manipulate a date but keep its existing format. I'm looking for a library/algorithm that does something akin to this:

Input: Jan 6

Output: %b %w

Is it doable?

CodePudding user response:

There's no need for a library. If you are thinking to "convert" the date string to its possible date format, you can use a function called strptime, and "reverse lookup" for a date string's possible date format like this:

import datetime as dt

mydates='''\
Jan 6
February 19
1 December
20 Sep
'''

matched_dateformats_list=[]

# You can expand this to include more variations and combinations of dateformats
dateformats = ('%b %d','%d %b', '%B %d','%d %B')

for date in mydates.splitlines():
    for dateformat in dateformats:
        try:
           # Check to see if strptime errors out, this way we know if the dateformate matches the date string format
           dateobject = dt.datetime.strptime(date, dateformat)

           # Append successful match
           matched_dateformats_list.append((date, dateformat)) 
           break
        except:
            # If it's not a match, skip, don't append, and continue to the next one
           continue

# Print the successful matches (date and the date format)
for (i,j) in matched_dateformats_list:
    print (i   " -> "   j)

Output:

Jan 6 -> %b %d
February 19 -> %B %d
1 December -> %d %B
20 Sep -> %d %b

The Python datetime formats can be found here:

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

There's a limitation though. If both your month and day is in numeric format this won't work.

CodePudding user response:

it was quite challenging to make it with regex, hope it will work:

from re import sub

dates = ['Jan 6','February 19','1 December','20 Sep']

def func(m):
    return f"%d %{['b','B'][bool(m[3])]}" if m[1] else f"%{['b','B'][bool(m[3])]} %d"

for date in dates:
    print(sub(r'(\d )?\s?([a-zA-Z]{3})([a-z] )?\s?(\d )?',func, date))

>>> out
'''
%b %d
%B %d
%d %B
%d %b
  • Related