I have a timezone aware datetime date object:
Timestamp('2004-03-29 00:00:00-0456', tz='America/New_York')
and a number of mili seconds since midnight (midnight in the local timezone):
34188542
How to combine them to get a valid datetime?
Create a timedelta object and add it to you time like this:
td = datetime.timedelta(milliseconds=34188542)
date_object = datetime.datetime.now() + td # change to your datetime object, I just use `now()`
Assuming the datetime object is ts, and by "combine them", you mean "add them":
ms = 34188545
new_datetime = ts + datetime.timedelta(milliseconds = ms)
Related
I need to convert a datetime into a string using numpy.
Is there another way to directly convert only one object to string that doesn't involve using the following function passing an array of 1 element (which returns an array too)?
numpy.datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')
With this function, I can make the conversion, but I just want to know if there is a more direct/clean way to do it.
Thanks in advance.
As we dont know what is inside of arr, I assume it is just datetime.now()
If so try this:
import datetime
datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
>>> '2022-07-28 10:27:34.986848'
If you need numpy version:
np.array(datetime.datetime.now(), dtype='datetime64[s]')
>>> array('2022-07-28T10:32:19', dtype='datetime64[s]')
if you just want to convert one numpy DateTime64 object into a string, here is the answer.
import datetime
yourdt = yourdt.astype(datetime.datetime)
yourdt_str = yourdt.strftime("%Y-%m-%d %H:%M:%S")
that's it
from datetime import datetime
now = datetime.now() # current date and time
year = now.strftime("%Y")
print("year:", year)
month = now.strftime("%m")
print("month:", month)
day = now.strftime("%d")
print("day:", day)
time = now.strftime("%H:%M:%S")
print("time:", time)
date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)
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
All answers require hour, min, s, etc...
like this:
from datetime import datetime
datetime.today() - datetime.timedelta(days=1)
I don't want to create datetime object that contain all hours, minutes, seconds, etc...
Is there a way to add and substract date on higher level(date?)
What I desire:
dt = "20210601"
st_date = dt - 30days
print(st_date)
>>> "2021-05-02"
What I tried:
datetime.strptime("20210601", "%Y%m%d") - datetime.timedelta(days=30)
Outputs AttributeError: type object 'datetime.datetime' has no attribute 'timedelta' which I assume it wants all hours, mins, seconds, etc...
Try using the timedelta function instead of the datetime.timedelta function:
from datetime import datetime, timedelta
stdate = datetime.strptime("20210601", "%Y%m%d") - timedelta(days=30)
print(stdate)
Output:
2021-05-02 00:00:00
I want to add a time to a datetime. My initial datetime is: initial_datetime='2015-11-03 08:05:22' and is a string and this_hour and this_min are strings too. I use:
time='-7:00'
time = time.split(':')
this_hour = time[0]
this_min = time[1]
initial_datetime='2015-11-03 08:05:22'
new_date = datetime.combine(initial_datetime, time(this_hour, this_min))
+ timedelta(hours=4)
But there comes an error:
'str' object is not callable.
My desired output is the initial_datetime plus my time (in this case -7 hours ) and then add 4 hours. So, in my example, the new date should be '2015-11-03 05:05:22'.
datetime.combine is typically used to combine a date object with a time object rather than incrementing or decrementing a datetime object. In your case, you need to convert your datetime string to a datetime object and convert the parts of your time string to integers so you can add them to your datetime with timedelta. As an aside, be careful about using variable names, like time, that conflict with your imports.
from datetime import datetime, timedelta
dtstr = '2015-11-03 08:05:22'
tstr = '-7:00'
hours, minutes = [int(t) for t in tstr.split(':')]
dt = datetime.strptime(dtstr, '%Y-%m-%d %H:%M:%S') + timedelta(hours=hours+4, minutes=minutes)
print(dt)
# 2015-11-03 05:05:22
Datetime objects hurt my head for some reason. I am writing to figure out how to shift a date time object by 12 hours. I also need to know how to figure out if two date time object's differ by say 1 minute or more.
The datetime library has a timedelta object specifically for this kind of thing:
import datetime
mydatetime = datetime.now() # or whatever value you want
twelvelater = mydatetime + datetime.timedelta(hours=12)
twelveearlier = mydatetime - datetime.timedelta(hours=12)
difference = abs(some_datetime_A - some_datetime_B)
# difference is now a timedelta object
# there are a couple of ways to do this comparision:
if difference > timedelta(minutes=1):
print "Timestamps were more than a minute apart"
# or:
if difference.total_seconds() > 60:
print "Timestamps were more than a minute apart"
You'd use datetime.timedelta for something like this.
from datetime import timedelta
datetime arithmetic works kind of like normal arithmetic: you can add a timedelta object to a datetime object to shift its time:
dt = # some datetime object
dt_plus_12 = dt + timedelta(hours=12)
Also you can subtract two datetime objects to get a timedelta representing the difference between them:
dt2 = # some other datetime object
ONE_MINUTE = timedelta(minutes=1)
if abs(dt2 - dt) > ONE_MINUTE:
# do something