In Python, the date object represents a calendar date consisting of a year, month, and day, while the datetime object represents a specific moment in time including both date and time components down to the microsecond.
Creating a date object: Use
datetime.date(year, month, day)ordate.today()to get the current date.Creating a datetime object: Use
datetime.datetime(year, month, day, hour, minute, second, microsecond)ordatetime.now()to get the current date and time.Converting datetime to date: Call the
.date()method on adatetimeobject (e.g.,datetime.now().date()) to extract only the date portion.Converting date to datetime: Use
datetime.combine(date_obj, time_obj)or instantiatedatetimewith the date object's attributes (e.g.,datetime(date_obj.year, date_obj.month, date_obj.day)).
The datetime module provides format codes for strftime() and strptime() to format or parse these objects, such as %Y for the year, %m for the month, and %d for the day.
Videos
Hello everyone, this is what my date column looks like:
| Date |
|---|
| 2023-11-30 23:20:12 |
| 2023-11-29 20:19:46 |
| 2023-11-28 21:33:25 |
| 2023-11-27 15:31:32 |
What I am trying to do it turn the dates in the column into this "2023-11-30" format only. So I am just trying to have the date and the time not be in the column. Can some please show me how to get rid of the time part of in the date column so that I am left with just this format for dates in the date column:
2023-11-30
You can use datetime.combine(date, time); for the time, you create a datetime.time object initialized to midnight.
from datetime import date
from datetime import datetime
dt = datetime.combine(date.today(), datetime.min.time())
There are several ways, although I do believe the one you mention (and dislike) is the most readable one.
>>> import datetime
>>> t=datetime.date.today()
>>> datetime.datetime.fromordinal(t.toordinal())
datetime.datetime(2009, 12, 20, 0, 0)
>>> datetime.datetime(t.year, t.month, t.day)
datetime.datetime(2009, 12, 20, 0, 0)
>>> datetime.datetime(*t.timetuple()[:-4])
datetime.datetime(2009, 12, 20, 0, 0)
and so forth -- but basically they all hinge on appropriately extracting info from the date object and ploughing it back into the suitable ctor or classfunction for datetime.
ยป pip install DateTime