Python Datetime Formatting Without Zero-Padding

Python datetime formatting without zero-padding

The formatting options available with datetime.strftime() will all zero-pad. You could of course roll you own formatting function, but the easiest solution in this case might be to post-process the result of datetime.strftime():

s = mydatetime.strftime('%m/%d/%Y %I:%M%p').lstrip("0").replace(" 0", " ")

Datetime Object without leading zero

You are confusing the formats of parsing (a string into a dt) and formatting (a dt into a string):

This works on linux (or online via http://pyfiddle.io):

import datetime 

dt = datetime.datetime.now()

# format datetime as string
print(datetime.datetime.strftime(dt, '%Y-%-m-%-d')) # - acts to remove 0 AND as delimiter

# parse a string into a datetime object
dt2 = datetime.datetime.strptime("1022-4-09", '%Y-%m-%d')

print(dt2)

Output:

2018-4-5
1022-04-09 00:00:00

The - when formatting a string acts to remove the leading 0 AND as delimiter - for parsing it only needs to be placed as delimiter - parsing works on on either 02 or 2 for %m


This works on Windows (VS2017):

from datetime import datetime, timedelta

loop_date = "1950-1-1"
date_obj = datetime.strptime(loop_date, '%Y-%m-%d')
date_obj += timedelta(days=1)
print(date_obj) # output the datetime-object

print(datetime.strftime(date_obj,'%Y-%#m-%#d')) # output it formatted

Output:

1950-01-02 00:00:00
1950-1-2

Format string to datetime in Pandas without zero padding, AM/PM and UTC

You can use %m/%d/%Y %H:%M:

pd.to_datetime(df['date'], dayfirst=False).dt.strftime('%m/%d/%Y %H:%M')

output:

0    10/12/2021 10:25
1 09/28/2021 08:51
2 07/27/2021 09:45
3 02/02/2022 19:10
Name: date, dtype: object

used input:

df = pd.DataFrame({'date': ['10/12/2021 10:25 AM UTC',
'9/28/2021 8:51 AM UTC',
'7/27/2021 9:45 AM UTC',
'2/2/2022 7:10 PM UTC']})

Convert String to Python datetime Object without Zero Padding

There is nothing wrong with this code:

>>> date = "09/10/2015 6:17:09 PM"
>>> date_obj = datetime.datetime.strptime(date, '%m/%d/%Y %I:%M:%S %p')
>>> date_obj
datetime.datetime(2015, 9, 10, 18, 17, 9)
>>> print(date_obj)
2015-09-10 18:17:09

The individual attributes of the datetime object are integers, not strings, and the internal representation uses 24hr values for the hour.

Note that I have swapped the day and month in the format strings as you state that the input format is mm/dd/yyyy.

But it seems that you actually want it as a string with zero padded hour, so you can use datetime.strftime() like this:

>>> date_str = date_obj.strftime('%m/%d/%Y %I:%M:%S %p')
>>> print(date_str)
09/10/2015 06:17:09 PM

# or, if you actually want the output format as %d/%m/%Y....
>>> print(date_obj.strftime('%d/%m/%Y %I:%M:%S %p'))
10/09/2015 06:17:09 PM

Parsing non-zero padded timestamps in Python

strptime is able to parse non-padded values. The fact that they are noted as being padded in the formatting codes table applies to strftime's output. So you can just use

datetime.strptime(datestr, "%m/%d/%Y %H:%M")

How do I parse a date without zero padding, in the format (1 or 2-digit year)-(Month abbreviation)?

It will be easier if 0 is padded to single digit years, as it can be directly converted to time using format. Regular expression is used here to replace any instance of single digit number with it's '0 padded in front' value. I've used regex from here.

Sample code:

import re
match_condn = r'\b([0-9])\b'
replace_str = r'0\1'
datetime.strptime(re.sub(match_condn, replace_str, '15-Jun'), '%y-%b').strftime("%B %Y")

Output:

June 2015

Parsing non-zero padded 12-hour datetime format in Python

You have day and month the wrong way round.

This should work.

from datetime import datetime 

datetime.strptime("3/31/21 1:50PM", '%m/%d/%y %I:%M%p')


Related Topics



Leave a reply



Submit