简体   繁体   中英

How to format '0000-00-00 00:00:00' using strftime() in python?

formatting date as:

dob = datetime(0000, 00, 00)
dob = dob.strftime("%Y-%m-%d")

but it gives error: ValueError: year is out of range

how can i format datetime(0000,00,00) using strftime() in python?

Python's documentation on the datetime module , particularly the datetime class states that the datetime object can have attribute values in the following range:

 MINYEAR <= year <= MAXYEAR 1 <= month <= 12 1 <= day <= number of days in the given month and year 0 <= hour < 24 0 <= minute < 60 0 <= second < 60 0 <= microsecond < 1000000

This module also defines the following constants:

datetime.MINYEAR

The smallest year number allowed in a date or datetime object. MINYEAR is 1 .

datetime.MAXYEAR

The largest year number allowed in a date or datetime object. MAXYEAR is 9999 .

which means that you cannot use those ( datetime(0000, 00, 00) ) parameters in the constructor of the datetime class, hence the ValueError stating that the given year is out of range

Since you can't construct a datetime object with the following arguments in the first place, there is no way to call the strftime method on it.

You cannot use a year/month/day of value 0.

dob = datetime(1989, 1, 1)
dob = dob.strftime("%Y-%m-%d")

'1989-01-01'

It is out of range - there's no year 0 in the Common Era, nor a month or day zero in the Gregorian calendar. Beyond that, if time_t is 32-bit you might not be able to process years before 1902 (a property of Unix time ).

If you really want to produce a string with zeros in it as an example of the format, you could generate one with some functioning date (such as 99-09-09) and replacing the digits with zeros.

In general I prefer sample dates from which you can infer the fields by their values, however, such as 1980-10-30. This doesn't leave room for confusing day and month.

日期、月份和年份不能为 0。如果您希望提供某种默认值,请考虑为其提供一个回溯值,例如 1970 年 1 月 1 日或任何其他年份在 1-9999 范围内、日期在 1-30 范围内的日期( 28,29,31(如适用)和 1-12 范围内的月份

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM