Killing two birds with one stone, I have two questions
How can I accurately call the current date? Current hour?
And how can I accurately call a specific hour? Not specific to a day.
from datetime import date, datetime
current_time = datetime.utcnow() # Call current time
start_time = datetime.time.hour(17)
end_time = datetime.time.hour(20)
You were pretty close to an answer. Here we go.
import datetime
after importing the datetime module you just need to call:
current_time = datetime.datetime.now()
In case you wanna access the data you have the year, month, day, hour, minute, second, microsecond methods:
current_time.day # Will return 17
To specify a given hour you just have to a variable you have the datetime.time class.
An idealized time, independent of any particular day, assuming that every day has exactly 246060 seconds. (There is no notion of “leap seconds” here.) Attributes: hour, minute, second, microsecond, and tzinfo.
start_time = datetime.time(17, 25, 30) # (17:25:30)
And the same as before. Accessing data can be done by calling its methods.
start_time.hour # will return 17
Here you have the documentation: :)
datetime module
Using the datetime module in Python
Examples given with Python 3
Get current time
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S") # H - hour, M- minute, S - second
print("Current Time =", current_time)
Get current hour
from datetime import datetime
now = datetime.now()
current_hour = now.strftime("%H")
print("Current hour =", current_hour)
Get current date
from datetime import date
today = date.today()
print("Today's date:", today)
Likewise, use %S for second, %M for minute, and %H for hour.
and %d for day, %m for month, and %Y for year.
Extras
Print date and time together
from datetime import datetime
# datetime object containing current date and time
now = datetime.now()
print("now =", now)
# dd/mm/YY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)
Print according to time-zone
from datetime import datetime
import pytz
tz_NY = pytz.timezone('America/New_York')
datetime_NY = datetime.now(tz_NY)
print("NY time:", datetime_NY.strftime("%H:%M:%S"))
tz_London = pytz.timezone('Europe/London')
datetime_London = datetime.now(tz_London)
print("London time:", datetime_London.strftime("%H:%M:%S
sources:
Date
Time
Also check out: Similar question
Related
I need to subtract 1 day from the current date and time? How would i do that?
Here is my code:
from datetime import datetime
now = datetime.now()
date = (now.strftime("%Y-%m-%d %H:%M:%S"))
print(date)
Say the date is (2021-10-3) i need the time variable to be set to something like (2021-10-2) Changing the day by -1 day!
Use timedelta.
from datetime import datetime, timedelta
now = datetime.now()
yesterday = now - timedelta(days=1)
date = (yesterday.strftime("%Y-%m-%d %H:%M:%S"))
print(date)
Find more about timedelta here
I am trying to do some testing with time offsets from UTC. I have tried two methods as shown in the code listing below:
Adding timedelta to UTC datetime
Using astimezone method on UTC datetime
In the short test program below the resultant date from astimezone method is 1 hour behind. I do not understand why??
from datetime import datetime, timedelta, timezone
if __name__ == "__main__":
utc_now = datetime.utcnow()
target_time = int((utc_now + timedelta(hours=10)).timestamp())
timestamp = utc_now.astimezone(timezone(timedelta(hours=10)))
print(f"datetime.utcnow() = {utc_now.isoformat()}")
print(
f"datetime.utcnow() + 10 hours using timedelta = {datetime.fromtimestamp(target_time).isoformat()}"
)
print(f"datetime.utcnow() + 10 hours using astimezone = {timestamp.isoformat()}")
datetime.utcnow() = 2021-09-04T16:12:53.753059
datetime.utcnow() + 10 hours using timedelta = 2021-09-05T02:12:53
datetime.utcnow() + 10 hours using astimezone = 2021-09-05T01:12:53.753059+10:00
Edit - Update - datetime.now (timezone.utc )
from datetime import datetime, timedelta, timezone
if __name__ == "__main__":
utc_now = datetime.now(timezone.utc)
target_time = int((utc_now + timedelta(hours=10)).timestamp())
timestamp = utc_now.astimezone(timezone(timedelta(hours=10)))
print(f"datetime.utcnow() = {utc_now.isoformat()}")
print(
"datetime.utcnow() + 10 hours using timedelta ="
f" {datetime.fromtimestamp(target_time).isoformat()}"
)
print(f"datetime.utcnow() + 10 hours using astimezone = {timestamp.isoformat()}")
Tried to make timezone aware UTC datetime now with the same result.
How do I use astimezone to get an equivalent result?
The problem here is the assumption that datetime.utcnow() gives you UTC. It does not. It gives you a naive datetime object that Python still treats as local time although hours, minutes etc. resemble UTC.
Set tzinfo adequately to get consistent results (don't use utcnow at all if possible! - unless you know what you're doing):
from datetime import datetime, timedelta, timezone
utc_now = datetime(2021, 9, 4, tzinfo=timezone.utc)
target_time = int((utc_now + timedelta(hours=10)).timestamp())
timestamp = utc_now.astimezone(timezone(timedelta(hours=10)))
print(f"utc_now = {utc_now.isoformat()}")
print(f"utc_now + 10 hours using timedelta = {datetime.fromtimestamp(target_time, tz=timezone.utc).isoformat()}")
print(f"utc_now + 10 hours using astimezone = {timestamp.isoformat()}")
# utc_now = 2021-09-04T00:00:00+00:00
# utc_now + 10 hours using timedelta = 2021-09-04T10:00:00+00:00
# utc_now + 10 hours using astimezone = 2021-09-04T10:00:00+10:00
The key here is understanding the difference between naive datetime (=local time by default) and aware datetime (the time zone you set...). For more time zone handling, see also the zoneinfo lib.
an aspect that is also relevant here in the context of working with time zones in Python: timedelta arithmetic is wall time arithmetic - i.e. what you would observe on a wall clock that gets adjusted to DST active/inactive. In the following example, I add 24 hours:
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
t0 = datetime(2021, 10, 30, 20, tzinfo=ZoneInfo("Europe/Berlin")) # DST active
t1 = t0 + timedelta(hours=24) # add 24 hours -> DST is inactive
print(t0, t1)
# 2021-10-30 20:00:00+02:00 2021-10-31 20:00:00+01:00
print((t1-t0).total_seconds()/3600)
# 24.0
Now watch how they become 25 hours - not because of magic but because of the wall clock would show local time, not UTC...
t0_utc, t1_utc = t0.astimezone(ZoneInfo("UTC")), t1.astimezone(ZoneInfo("UTC"))
print(t0_utc, t1_utc)
# 2021-10-30 18:00:00+00:00 2021-10-31 19:00:00+00:00
print((t1_utc-t0_utc).total_seconds()/3600)
# 25.0
Note: since Europe/Berlin is the time zone my OS is configured to use, this would also work with t0 and t1 being naive datetime objects!
I have a time from five minutes ago, using datetime.time.now() and I need to know what the time would be if I subtracted that time from the current time.
Try 1 - Didn't Work:
from datetime import datetime, timedelta
time1 = datetime.now()
time2 = datetime.now() + timedelta(minutes=5)
print(time1 - time2)
This gave me "-1 day, 23:54:59.999987".
Try 2 - Worked, but is there a better way?:
time1 = datetime.now()
time2 = datetime.now() + timedelta(minutes=5)
print(str(time1 - time2).split(',')[1])
This gave me the desired result, but is there a method besides string manipulation?
You wanted to take an advice how to use a time object?
Well, if you want to specify a format of string representation of your time, just use strftime
Example below:
from datetime import datetime, timedelta
time1 = datetime.now()
time2 = datetime.now() + timedelta(minutes=5)
print((time1 - time2).strftime('%H:%M:%S'))
Assuming you want the time 5 minutes ago, you can use timedelta without any string manipulation:
five_min_ago = datetime.datetime.now() - datetime.timedelta(minutes = 5)
I am taking time as input from the user in the HH:MM format. Let's say 00:00 and now I want to keep adding a minute to the time and make it 00:01, 00:02 and so on.
Also, I am taking two inputs form the user start_time and end_time as strings. How can I calculate the difference between the two times as well in minutes?
I am new to Python and any help would be appreciated!
I am using the below code:
#to calculate difference in time
time_diff = datetime.strptime(end_time, '%H:%M') - datetime.strptime(start_time, '%H:%M')
minutes = int(time_diff.total_seconds()/60)
print minutes
#to convert string to time format HH:MM
start_time = datetime.strptime(start_time, '%H:%M').time()
#to increment time by 1 minute
start_time = start_time + datetime.timedelta(minutes=1)
I am not able to increment the start_time using timedelta.
import datetime
time_diff = datetime.datetime.strptime(end_time, '%H:%M') - datetime.datetime.strptime(start_time, '%H:%M')
minutes = int(time_diff.total_seconds()/60)
print minutes
datetime is a class of the datetime module that has a classmethod called strptime. The nomenclature is a bit confusing, but this should work as you intend it to.
As for adding a time delta, you'll need store the start time as a datetime object in order to get that to work:
start_datetime = datetime.datetime.strptime(start_time, '%H:%M')
start_datetime = start_datetime + datetime.timedelta(minutes=1)
print start_datetime
First part of your question, you can use the datetime module:
from datetime import datetime as dt
from datetime import timedelta as td
UsrInput = '00:00'
fmtString = '%H:%M'
myTime = dt.strptime(UsrInput, fmtString)
increment = td(0,1)
for count in range(10):
myTime += increment
print (dt.strftime(myTime, fmtString))
Second part will also use datetime, as such:
from datetime import datetime as dt
from datetime import timedelta as td
start_time = '00:01'
end_time = '00:23'
fmtString = '%H:%M'
myStart = dt.strptime(start_time, fmtString)
myEnd = dt.strptime(end_time, fmtString)
difference = myEnd - myStart
print(td.strftime(difference, '%M')
I'm trying to get my head around the datetime module. I know the time now as an epoch and the time an event last happened (as an epoch time). What I need to do is figure out whether that event happened between midnight and midnight of yesterday.
t = time.time() # is now
t2 = 1234567890 # some arbitrary time from my log
24 hours ago is t - 86400, but how can I round that up and down to midnight. I'm having real trouble finding a way to get timestamps in and out of datetime or then manipulating a datetime to set the time.
In the Middle of the Night
Generating the last midnight is easy:
from datetime import datetime, time
midnight = datetime.combine(datetime.today(), time.min)
That combines today's date (you can use date() or a datetime() instance, your pick), together with time.min to form a datetime object at midnight.
Yesterday
With a timedelta() you can calculate the previous midnight:
from datetime import timedelta
yesterday_midnight = midnight - timedelta(days=1)
That Was Yesterday
Now test if your timestamp is in between these two points:
timestamp = datetime.fromtimestamp(some_timestamp_from_your_log)
if yesterday_midnight <= timestamp < midnight:
# this happened between 00:00:00 and 23:59:59 yesterday
All Together Now
Combined into one function:
from datetime import datetime, time, timedelta
def is_yesterday(timestamp):
midnight = datetime.combine(datetime.today(), time.min)
yesterday_midnight = midnight - timedelta(days=1)
return yesterday_midnight <= timestamp < midnight:
if is_yesterday(datetime.fromtimestamp(some_timestamp_from_your_log)):
# ...
Midnight at the start of today is:
midnight = (int(time.time() // 86400)) * 86400
so yesterday's midnight is:
midnight = (int(time.time() // 86400)) * 86400 - 86400
Given such a timestamp, you can use divmod to compute the number of days since the epoch (which you don't care about), and how many seconds are leftover (which you do):
days_since, remaining_seconds = divmod(t, 24*3600) # Divide by number of seconds in one day
Then, you subtract the leftover seconds from your original timestamp, which produces midnight
of the current day.
t -= remaining_seconds
Rounding up is as simple as shifting your target timestamp forward exactly one day before rounding down.
tomorrow_t = t + 24 * 3600
days_since, remaining_seconds = divmod(tomorrow_t, 24*3600)
t = tomorrow_t - remaining_seconds
To get the specific timezone's midnight timestamp:
from datetime import datetime
import pytz
TZ = "Asia/Shanghai"
datetime.now(pytz.timezone(TZ)).replace(hour=0, minute=0, second=0, microsecond=0).timestamp()
In my estimation, many date and time manipulations are easier to do, and to understand, using the arrow library. This is one of them.
Create an arbitrary date and time.
>>> import arrow
>>> arbitrary = arrow.get(2017,8,16,11,5)
Calculate midnight_yesterday: first, midnight of arbitrary as its 'day' floor; then shift this back by one day. Display the result.
>>> midnight_yesterday = arbitrary.floor('day').shift(days=-1)
>>> midnight_yesterday
<Arrow [2017-08-15T00:00:00+00:00]>
Use timestamp for the desired overall result, for Python 3.3+.
>>> midnight_yesterday.datetime.timestamp()
1502755200.0
Or use this expression for Python 2.7. (Credit: https://stackoverflow.com/a/11743262/131187 for the latter two expressions.)
>>> (midnight_yesterday-arrow.get(1970,1,1)).total_seconds()
1502755200.0
You can use this code:
import time
seconds_of_day = 24 * 60 * 60 # 86400
last_midnight = (round(time.time()) // seconds_of_day) * seconds_of_day
yesterday_last_midnight = last_midnight - seconds_of_day
import time
start_str = time.strftime( "%m/%d/%Y" ) + " 00:00:00"
end_str = time.strftime( "%m/%d/%Y ") + " 23:59:59"
start_ts = int( time.mktime( time.strptime( start_str, "%m/%d/%Y %H:%M:%S" ) ) )
end_ts = int( time.mktime( time.strptime( end_str, "%m/%d/%Y %H:%M:%S" ) ) )
print (start_ts) # timestamp today at 00:00:00
print (end_ts) # timestamp today at 23:59:59
# 1552435200
# 1552521599
Source Python get unix epoch for today’s midnight and today’s 23:59:59 (start of day, end of day)