11

Obviously I can get the date and time from datetime.datetime.now(), but I don't actually care about the seconds or especially microseconds.

Is there somewhere I can easily get Date+Hour+Minute?

Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
  • 2
    Just use the bits you need from the datetime type. dt.hour, dt.minute, dt.day, dt.month, dt.year - or if it's just a presentation issue, use the appropriate format string. What problem are you trying to solve? – Steve Mayne Dec 12 '12 at 11:11

1 Answers1

23

You can clear down the second and microsecond component of a datetime value like so:

dt = datetime.datetime.now()
#Now get rid of seconds and microseconds component:
dt = dt.replace(second=0, microsecond=0)

This would allow you to compare datetimes to minute granularity.

If you just want to print the date without a second/microsecond component, then use the appropriate format string:

dt = datetime.datetime.now()
print dt.strftime("%Y/%m/%d %H:%M")

>>> '2012/12/12 12:12'
Steve Mayne
  • 22,285
  • 4
  • 49
  • 49
  • This is perfect - I actually came across the `replace` function just after I posted this, and it was exactly what I needed. – Wayne Werner Dec 12 '12 at 11:25
  • 2
    Depending on what you're doing, you might do a rounding operation on the quantity minutes+seconds+microsecsonds to the nearest minute and modify the that attribute according. For example 15:45:17 (m:s:μ) would become 16:00:00. – martineau Dec 12 '12 at 13:48
  • Example of function rounding to seconds: [How to change datetime resolution](https://stackoverflow.com/a/72592640/320437) – pabouk - Ukraine stay strong Jun 12 '22 at 13:37