I am subtracting two dates in python 2.7 and getting wrong result in seconds. Apparently difference between these dates is more than 24h which is 86400s. But I am getting 44705s, why is that and how to fix it ?
>>> date1
datetime.datetime(2017, 10, 22, 11, 41, 28)
>>> date2
datetime.datetime(2017, 10, 20, 23, 16, 23)
>>> (date1-date2).seconds
44705
Calling .seconds will only give you the seconds component of the timedelta object, which only takes into account seconds, minutes, and hours (see docs for more detail). If you want the entire timedelta in seconds, call total_seconds.
>>> (date1 - date2).total_seconds()
131105.0
date1-date2 is datetime.timedelta(1, 44705). You're only looking at the seconds portion. Look at the days portion too.
Related
I want to have the current time without the seconds.
I use this: int(round(time.time() * 1000)) to get the current time, I get this as result:1589835912648
But when I transform (using datetime.fromtimestamp(int(1589835912648/1000)) ) it to something readable, I get this: datetime.datetime(2020, 5, 18, 23, 5, 12)
which is normal. But I want to get rid of the seconds!
like datetime.fromtimestamp(int(1589746140000/1000)) which gives: datetime.datetime(2020, 5, 17, 22, 9)
So, it gives the time without the seconds.
How can I do this?
I already tried round(int(round(time.time() * 1000)),-4) but that also gives me the seconds
Hope this is clear and that someone can help me
If you are fine with using something other than datetime, here:
import time
print(time.strftime("%H:%m"))
This will print the time in hours and minutes.
Hope this helps!
datetime.datetime is good for this because you can access each field easily by name:
>>> from datetime import datetime
>>> now = datetime.now()
>>> now.hour, now.minute
(14, 17)
or you can turn it into a string with strftime:
>>> datetime.now().strftime("%H:%M")
'14:17'
from datetime import datetime
current_time = datetime.now()
hour = current_time.hour
minute = current_time.minute
print(f"{hour}:{minute}")
Have two data sets with different time format. One in epcoh time, seconds from 1/1/1970, and the other hours since 1/1/1900. Need to convert the first to the second one. How can I do that in python ?
Thanks
So, for starters, here are the necessary tools:
from datetime import datetime, timezone, timedelta
Then you need to establish the starting time:
atmos_epoch = datetime(1900, 1, 1, 0, 0, tzinfo=timezone.utc)
Then you can work with deltas to that time:
>>> d = datetime.now(timezone.utc) - atmos_epoch
>>> d
datetime.timedelta(days=43893, seconds=28215, microseconds=982930)
>>> d.total_seconds() / 60 / 60
1053439.8377730362
That last value is the difference in hours.
You can add deltas to that epoch timestamp:
>>> atmos_epoch + timedelta(hours=1000000)
datetime.datetime(2014, 1, 29, 16, 0, tzinfo=datetime.timezone.utc)
The other thing you talk about, seconds since 1970, are simply UNIX timestamps, which you can work with easily:
>>> datetime.now().timestamp()
1583395060.91666
>>> datetime.fromtimestamp(1500000000)
datetime.datetime(2017, 7, 14, 4, 40)
Now you have a way to convert from both values to datetime objects and from datetime objects to either value.
This question already has answers here:
Stripping off the seconds in datetime python
(5 answers)
Closed 4 years ago.
When i preform datetime.now() to get the current time, it gets printed (with print) like this:
2018-06-14 13:21:02.331933
I want to ignore seconds and microseconds and to have it printed out like this:
2018-06-14 13:21:00
I know that I can convert to a string of my choosing with strftime but i'm not looking to alter the string but to change the datetime object itself so that it has 0 seconds and 0 milliseconds (and it seems stupid to do strftime and immediately strptime to convert back).
In other words to convert from datetime(2018, 6, 14, 14, 7, 27, 326853) to datetime(2018, 6, 14, 14, 7)
I've tried like this:
now = datetime.now()
now = now - timedelta(seconds=now.second, microseconds=now.microsecond)
And that works, but i'm sure there's a simpler and more efficient way (I need to do this thousands of times when iterating through different files). So my question is if i'm right that there is a simpler way and if so what are your solutions to such a problem?
Use datetime.replace:
now = datetime.now().replace(second=0, microsecond=0)
Use the datetime.replace() method to create a new instance, with specific attributes set to your desired value:
now = datetime.now().replace(second=0, microsecond=0)
Demo:
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2018, 6, 14, 12, 16, 4, 738362)
>>> datetime.now().replace(second=0, microsecond=0)
datetime.datetime(2018, 6, 14, 12, 16)
I have time defined in the following format: "%A %H:%M:%S" i.e "Monday 06:00:00"
Now, using the above format, I define a time window:
"Monday 06:00:00" - "Monday 18:00:00"
I now want to check if the current time falls within the time window or not. To do that, I am using the datetime utility.
import datetime
# current time in str
current_time = datetime.datetime.strftime(datetime.datetime.now(),'%A %H:%M:%S')
# convert to datetime object
current_time = datetime.datetime.strptime(current_time, '%A %H:%M:%S')
# print current_time produces: 1900-01-01 19:13:53
# and day of week information is lost
However, the moment, I convert the current_time to a datetime object, the day of the week information is lost.
What's the best way to compare time windows that includes day-of-week in Python?
BTW: I want the time window to be repeated in the future. For eg, "Monday 06:00 - Tuesday 05:00" would apply to all weeks in the future.
datetime would know nothing about which monday you're talking about. There have been 1000's since the epoch.
I suggest you look into the dateutil package. It applies "human-ish" semantics:
>>> import dateutil.parser
>>> dateutil.parser.parse('Monday')
datetime.datetime(2014, 2, 3, 0, 0)
>>> dateutil.parser.parse('Monday 18:30:00')
datetime.datetime(2014, 2, 3, 18, 30)
Note how it assumes that Monday means today (it's Monday). And Tuesday and Sunday (below) mean this coming Tuesday, Sunday:
>>> dateutil.parser.parse('Tuesday 18:30:00')
datetime.datetime(2014, 2, 4, 18, 30)
>>> dateutil.parser.parse('Sunday 18:30:00')
datetime.datetime(2014, 2, 9, 18, 30)
To take this further one take a look at the rrule module/class in dateutil. And the built-in calendar module. For example, with rrule I can do:
next_five = rrule.rrule(
rrule.WEEKLY,
count=5,
dtstart=dateutil.parser.parse('Sunday 18:30:00'),
)
This returns an iterator of the next 5 weeks starting at 6:30pm Sunday. The iterator will produce
[datetime.datetime(2014, 2, 5, 18, 30),
datetime.datetime(2014, 2, 12, 18, 30),
datetime.datetime(2014, 2, 19, 18, 30),
datetime.datetime(2014, 2, 26, 18, 30),
datetime.datetime(2014, 3, 5, 18, 30)]
This should get you going on the final solution.
In my experience Datetime objects are YYYY:MM:DD HH:MM:SS (more or less). The day of week can be derived from that object using datetime's weekday() - see http://docs.python.org/2/library/datetime.html#datetime.date.weekday
You can solve your problem using greater/less than "<" and ">" operators for datetime evaluation. Here is a proof for simple comparison http://pastebin.com/miTUW9nF
Your logic would be (paraphrased): "if Xtime > windowstart and Xtime < windowend then Xtime is in window"
Datetime compares down to the second, my example is now and (now-10 days), that should cover your needs.
I have encountered this problem today and I don't have an explanation for it.
I have a Python datetime object:
dt = datetime.datetime(2012, 3, 31, 18, 30, 48, tzinfo=<FixedOffset '-04:00'>)
which, to my understanding is 18:30 in a time zone offset from UTC by 4 hours.
I then tried to convert it to timestamp like so:
epo = time.mktime(dt.timetuple()) and get back 1333247448.0.
However, when I try to convert it back to make sure it's correct using date
time.datetime.fromtimestring(epo),
I get back
datetime.datetime(2012, 3, 31, 19, 30, 48)
Notice that time is 19 not 18.
Can anybody tell me why it's doing that?
Try using
time.localtime(epo)
instead of
time.datetime.fromtimestring(epo)