Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the inverse of date.toordinal() in python?

Tags:

python

date

In python, a dateobject can be converted in the proleptic Gregorian ordinal this way:

d=datetime.date(year=2010, month=3, day=1)
d.toordinal()

but what is the reverse operation?

like image 599
Mermoz Avatar asked May 14 '13 11:05

Mermoz


People also ask

What is Toordinal in Python?

toordinal() is a simple method used to manipulate the objects of DateTime class. It returns proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. The function returns the ordinal value for the given DateTime object.

What does date () do in Python?

The date class is used to instantiate date objects in Python. When an object of this class is instantiated, it represents a date in the format YYYY-MM-DD. Constructor of this class needs three mandatory arguments year, month and date.

How do I strip a date in Python?

You just forgot to use %d in order to capture the date number and the : for the time and you ALSO need to capture +0000 . Show activity on this post.

How do I convert a date to another format in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.


2 Answers

The opposite is date.fromordinal

classmethod date.fromordinal(ordinal)

    Return the date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1. ValueError is raised unless 1 <= ordinal <= date.max.toordinal(). For any date d, date.fromordinal(d.toordinal()) == d.

like image 148
Jon Clements Avatar answered Sep 19 '22 16:09

Jon Clements


It's date.fromordial() as Jon wrote in the comments.

or datetime.fromordinal()

You can read more about it in the date= documentation

and for datetime

From the docs:

classmethod date.fromordinal(ordinal)

Return the date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1. ValueError is raised unless 1 <= ordinal <= date.max.toordinal().

For any date d, date.fromordinal(d.toordinal()) == d.

like image 21
Ewan Avatar answered Sep 22 '22 16:09

Ewan