Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date to ordinal python?

I want to convert 2010-03-01 to 733832

I just found this toordinal code

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

from this

But i want something more like

d=datetime.date('2010-03-01')
d.toordinal()

Thanks in advance

like image 568
Remn Avatar asked Oct 04 '16 07:10

Remn


People also ask

What is ordinal date 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.

How do I change the data type of a date in Python?

The date column is indeed a string, which—remember—is denoted as an object type in Python. You can convert it to the datetime type with the . to_datetime() method in pandas .

How do you convert date to mm/dd/yyyy in Python?

Use strftime() function of a datetime class For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

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.


2 Answers

You'll need to use strptime on the date string, specifying the format, then you can call the toordinal method of the date object:

>>> from datetime import datetime as dt
>>> d = dt.strptime('2010-03-01', '%Y-%m-%d').date()
>>> d
datetime.date(2010, 3, 1)
>>> d.toordinal()
733832

The call to the date method in this case is redundant, and is only kept for making the object consistent as a date object instead of a datetime object.

If you're looking to handle more date string formats, Python's strftime directives is one good reference you want to check out.

like image 183
Moses Koledoye Avatar answered Oct 19 '22 09:10

Moses Koledoye


like this:

datetime.strptime("2016-01-01", "%Y-%m-%d").toordinal()
like image 5
Howardyan Avatar answered Oct 19 '22 09:10

Howardyan