paulowe
paulowe

Reputation: 143

How to keep leading zeros in datetime to string conversion?

I am facing an issue whenever I try to convert a datetime object into string that has leading zeros in the year

Suppose d is my datetime object:

d = '0021-01-12 03:12:28'

d_str = d.strftime("%Y-%m-%d %H:%M:%S.%f")

The output of printing d_str is always (regardless of %Y or %y)

'21-01-12 03:12:28.000000'

The desired output should have leading zeros for the year

'0021-01-12 03:12:28.000000'

The datetime documentation suggests one of %y or %Y format codes should work, however, I have tried both options and they do not work.

Is there a way to do this using the datetime library or do I need to write custom logic?

Upvotes: 0

Views: 468

Answers (1)

Jordan Hyatt
Jordan Hyatt

Reputation: 434

Try this (edited to reflect suggestion in comment)

d.strftime("%y-%m-%d %H:%M:%S.%f").zfill(26)

Upvotes: 1

Related Questions