Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I easily get datetime with less resolution in Python?

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?

like image 786
Wayne Werner Avatar asked Dec 12 '12 11:12

Wayne Werner


People also ask

How to work with dates and times in Python?

Python has a module named datetime to work with dates and times. Let's create a few simple programs related to date and time before we dig deeper. When you run the program, the output will be something like: Here, we have imported datetime module using import datetime statement. One of the classes defined in the datetime module is datetime class.

How to check if one DateTime is less than other datetime in Python?

Check if One DateTime is Less than other DateTime. You can use less than comparison operator < to check if one datetime object is less than other. In the following program, we initialize two datetime objects, and then compare if first one is less than second. Python Program

How to compare two Python objects with different dates?

Python Compare DateTime. When you have two datetime objects, the date and time one of them represent could be earlier or latest than that of other, or equal. To compare datetime objects, you can use comparison operators like greater than, less than or equal to. Like any other comparison operation, a boolean value is returned.

Is there a way to display time zone information in Python?

Python datetime provides tzinfo, which is an abstract base class that allows datetime.datetime and datetime.time to include time zone information, including an idea of daylight saving time. However, datetime does not provide a direct way to interact with the IANA time zone database.


1 Answers

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'
like image 118
Steve Mayne Avatar answered Sep 24 '22 07:09

Steve Mayne