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
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.
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 .
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.
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.
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 this:
datetime.strptime("2016-01-01", "%Y-%m-%d").toordinal()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With