How can I create a date time object for 9:00 AM UTC to use for comparison with the current utc time?
new_date = datetime.datetime(2019, 12, 2, 10, 24, 34, 198130)
I want to do it without the year, minutes and seconds.
If you don't need the date part of it, use datetime.time:
import datetime
nine_am = datetime.time(9)
if datetime.datetime.utcnow().time() > nine_am:
...
Related
Basically, I got:
tz = pytz.timezone('US/Eastern')
dt = datetime.datetime(2019, 03, 10, 02, 30)
I want to localize dt to the timezone while removing the non-existing hour.
If I do tz.normalize(tz.localize(dt)), I'll get
datetime.datetime(2019, 3, 10, 3, 30, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>)
I want
datetime.datetime(2019, 3, 10, 3, 00, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>)
(use 03:00 instead of 03:30 since it's closer to 02:30 wall-clock).
The usecase:
I got a list of wall-times (one of them happens to be 02:30), datetime of 2019-03-10 and timezone US/Eastern.
I want to construct the timestamps in the specific datetime and timezone with using 03:00 (well, actually the time right after DST leap) instead of any wall-time that will become invalid when I combine timestamp with datetime and localize it. It's done to automatically copy some list of appointments that are tied to wall-clock times to another day.
def localize_and_round_datetime(dt, tz):
"""
Similar to tz.normalize(tz.localize(dt)), but rounds any time in non-existing hour to the time right after it.
"""
result = tz.normalize(tz.localize(dt))
if result.replace(tzinfo=None) == dt:
return result
# DT belongs to the leap hour. find the datetime right after leap
# see: DstTzInfo.localize()
tzinfo_dst_idx = bisect_right(tz._utc_transition_times, dt)
new_tz = tz._utc_transition_times[tzinfo_dst_idx]
return pytz.UTC.localize(new_tz).astimezone(tz)
seems to work.
I have a unix timestamp in seconds (such as 1294778181) that I can convert to UTC using
from datetime import datetime
datetime.utcfromtimestamp(unix_timestamp)
Problem is, I would like to get the corresponding time in 'US/Eastern' (considering any DST) and I cannot use pytz and other utilities.
Only datetime is available to me.
Is that possible?
Thanks!
Easiest, but not supersmart solution is using timedelta
import datetime
>>> now = datetime.datetime.utcnow()
US/Eastern is 5 hours behind UTC, so let's just create thouse five hours as a timedelta object and make it negative, so that when reading back our code we can see that the offset is -5 and that there's no magic to deciding when to add and when to subtract timezone offset
>>> eastern_offset = -(datetime.timedelta(hours=5))
>>> eastern = now + eastern_offset
>>> now
datetime.datetime(2016, 8, 26, 20, 7, 12, 375841)
>>> eastern
datetime.datetime(2016, 8, 26, 15, 7, 12, 375841)
If we wanted to fix DST, we'd run the datetime through smoething like this (not entirely accurate, timezones are not my expertise (googling a bit now it changes each year, yuck))
if now.month > 2 and now.month < 12:
if (now.month == 3 and now.day > 12) or (now.month == 11 and now.day < 5):
eastern.offset(datetime.timedelta(hours=5))
You could go even into more detail, add hours, find out how exactly it changes each year... I'm not going to go through all that :)
I have a mongodb time as objectid("5217a543dd99a6d9e0f74702").
How to convert it to epoch time in Python. (UTC timezone and also EST timezone)
ObjectId.generation_time gives you the time the ObjectId was generated, in UTC:
>>> from bson import ObjectId
>>> ObjectId("5217a543dd99a6d9e0f74702").generation_time
datetime.datetime(2013, 8, 23, 18, 9, 7, tzinfo=<bson.tz_util.FixedOffset object at 0x102920c90>)
The documentation is here.
To convert to Eastern Time, install pytz and:
>>> import pytz
>>> ny = pytz.timezone('America/New_York')
>>> gt = ObjectId("5217a543dd99a6d9e0f74702").generation_time
>>> ny.normalize(gt.astimezone(ny))
datetime.datetime(2013, 8, 23, 14, 9, 7, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>)
You can use the ObjectId.getTimestamp() method to get the timestamp portion of the objectid as Date.
Once you have the Date object you can call any of the Date methods to get what you want. In the shell, you could just hit TAB to get the list of all methods that are permitted:
> var myid = new ObjectId()
> myid
ObjectId("5331ba8163083f9b26efb5b3")
> var mytime = myid.getTimestamp()
> mytime
ISODate("2014-03-25T17:18:57Z")
> mytime.<TAB>
mytime.constructor mytime.getUTCFullYear(
mytime.getDate( mytime.getUTCHours(
mytime.getDay( mytime.getUTCMilliseconds(
mytime.getFullYear( mytime.getUTCMinutes(
mytime.getHours( mytime.getUTCMonth(
mytime.getMilliseconds( mytime.getUTCSeconds(
mytime.getMinutes( mytime.getYear(
mytime.getMonth( mytime.hasOwnProperty(
mytime.getSeconds( mytime.propertyIsEnumerable(
mytime.getTime( mytime.setDate(
mytime.getTimezoneOffset( mytime.setFullYear(
mytime.getUTCDate( mytime.setHours(
mytime.getUTCDay( mytime.setMilliseconds(
Note: I'm not familiar with Python, but the same concepts would apply
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 a date time of my django object but it can be any time of the day. It can be at any time through the day, but I need to set my time to 00:00:00 (and another date to 23:59:59 but the principle will be the same)
end_date = lastItem.pub_date
currently the end date is 2002-01-11 12:34:56
What do I need to do to get this to change it to 00:00:00?
i tried:
end_date.hour = '00'
but got: 'datetime.datetime' object attribute 'time' is read-only
Using datetimes's "combine" with the time.min and time.max will give both of your datetimes.
For example:
from datetime import date, datetime, time
pub_date = date.today()
min_pub_date_time = datetime.combine(pub_date, time.min)
max_pub_date_time = datetime.combine(pub_date, time.max)
Result with pub_date of 6/5/2013:
min_pub_date_time -> datetime.datetime(2013, 6, 5, 0, 0)
max_pub_date_time -> datetime.datetime(2013, 6, 5, 23, 59, 59, 999999)
Try this:
import datetime
pub = lastItem.pub_date
end_date = datetime.datetime(pub.year, pub.month, pub.day)
Are you sure you don't want to use dates instead of datetimes? If you're always setting the time to midnight, you should consider using a date. If you really want to use datetimes, here's a function to get the same day at midnight:
def set_to_midnight(dt):
midnight = datetime.time(0)
return datetime.datetime.combine(dt.date(), midnight)
For tz-aware dates it should be:
datetime.combine(dt.date(), datetime.min.time(), dt.tzinfo)
datetime instance attributes like year, month, day, hour, etc are read-only, so you just have to create a new datetime object and assign it to end_date.