Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datetime Object without leading zero

I've come across several answers (1, 2, 3) regarding the removal of leading zeros on python3 datetime objects.

One of the most voted answers states:

On Windows, you would use #, e.g. %Y/%#m/%#d

The code above doesn't work for me. I've also tried the Linux solution, which uses - instead of #, without success.

Code:

loop_date = "1950-1-1"
date_obj = datetime.strptime(loop_date, '%Y-%m-%d') # or '%Y-%#m-%#d' which produces the errors below
date_obj += timedelta(days=1)
print(date_obj)
# This the prints `1954-01-02` but I need `1954-1-2`

Traceback:

Traceback (most recent call last):
  File "C:/collect_games.py", line 84, in <module>
    date_obj = datetime.strptime(loop_date, '%Y-%-m-%d')
  File "E:\Anaconda3\lib\_strptime.py", line 565, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "E:\Anaconda3\lib\_strptime.py", line 354, in _strptime
    (bad_directive, format)) from None
ValueError: '#' is a bad directive in format '%Y-%#m#%d'

What's most pythonic approach to this problem?

like image 230
Pedro Lobito Avatar asked Jul 28 '26 15:07

Pedro Lobito


1 Answers

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
like image 84
Patrick Artner Avatar answered Jul 30 '26 03:07

Patrick Artner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!