Home > Software design >  How to convert date to datetime in python
How to convert date to datetime in python

Time:06-02

Code:

def func(y, m):
for i in range(1, calendar.monthrange(y, m)[1] 1):
    th_date = date(y, m, i)
    print(th_date)
func(2020,4)

Note: i am getting dates as date format i want to convert it into datetime i don't want time

CodePudding user response:

You might just use datetime in place of date as 4th and following arguments to datetime.datetime are optional, so

import datetime
dt = datetime.datetime(2022,6,2)
print(dt)

gives output

2022-06-02 00:00:00

CodePudding user response:

If you're not interested in time but you want to use the datetime module then you can use the date class. For example:

from datetime import date

def func(year, month, day=1):
    return date(year, month, day)

print(func(2022, 4))

Output:

2022-04-01
  • Related