python datetime calculation not trimming to milliseconds - python

Doing the following calculation to take 30 days of the current date using the date-time module. The calculation is correct but it's not trimming milliseconds to 3 digits. any idea how I can implement it?
from datetime import datetime,timedelta
datetime_limit = datetime.today().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
datetime_limit = datetime.today() - timedelta(days=30)

The last digits are added when you do the calculation with timedelta.
from datetime import datetime,timedelta
datetime_limit = str(datetime.today() - timedelta(days=30))[:-3]
print(datetime_limit)

Related

Is there a function in python that could generate date 4 weeks from current date/given date?

Is there any function in python that can generate date for example 4 weeks from now or given date?
I've gone through documentation from datetime modeule but couldnt find any example that can support my question.
four_weeks = datetime.timedelta(days=4*7)
dt = datetime.datetime.now()
print(dt + four_weeks)
Here you go:
from datetime import timedelta
from datetime import datetime
today = datetime.today()
print(today + timedelta(weeks=1))
I think the thing you're looking for is timedelta.
from datetime import timedelta
def add_weeks(dt, n_weeks):
n_days = 7 * n_weeks
return dt + timedelta(days=n_days)
In python datetime module has a class called datetime which represents a date + time, an point on time line. There is another class called timedelta that represents difference between two dates (datetiems).
You can add a date with a timedelta.
example code:
from datetime import datetime, timedelta
now = datetime.now()
duration = timedelta(days=28)
target = now + duration
print(target)

Convert unix timestamp in Python to datetime and make 2 Hours behind

I have this code, recieve a unix timestamp from a server which is 2 hours ahead of my time. My time is SAST and theirs is GMT +2.
I convert this timestamp in python to a readable datetime like this
import datetime
unixtimestamp = 1507126064
datetime.datetime.fromtimestamp(unixtimestamp).strftime('%Y-%m-%d %H:%M:%S')
The problem is that this time comes back two hours ahead of me, so what would be the easiest way to minus two hours or make it local time.
With datetime.timedelta object:
from datetime import datetime, timedelta
unix_ts = 1507126064
dt = (datetime.fromtimestamp(unix_ts) - timedelta(hours=2)).strftime('%Y-%m-%d %H:%M:%S')
print(dt)

Convert local time to UNIX

I'm new to python and I'm trying to get the actual minutes passed every day since 7:00.
I am using mktime to get now_date1 and now_date2 in seconds, and then the plan it's to subtract and divide by 60 to get the minutes.
But I get the following error:
AttributeError: 'str' object has no attribute 'timetuple'
It's this the correct approach?
Here it's the code
import time
import pytz
from datetime import datetime
from time import mktime as mktime
now_date = datetime.now(pytz.timezone('Europe/Bucharest'))
now_date1 = now_date.strftime('%H:%M:%S')
now_date2 = now_date.strftime('7:00:00')
# Convert to Unix timestamp
d1_ts = time.mktime(now_date1.timetuple())
strftime returns a string. Not what you want.
You were pretty close, but there's no need to put time in the mix. Just modify your code like this and use time delta from datetime (inspired by How to calculate the time interval between two time strings):
import pytz
from datetime import datetime
now_date = datetime.now(pytz.timezone('Europe/Bucharest'))
from datetime import datetime
FMT = '%H:%M:%S'
now_date1 = now_date.strftime(FMT)
now_date2 = now_date.strftime('7:00:00')
tdelta = datetime.strptime(now_date1, FMT) - datetime.strptime(now_date2, FMT)
print(tdelta)
I get: 6:40:42 which seems to match since it's 12:42 here.
To get the result in minutes just do:
tdelta.seconds//60
(note that the dates have only correct hour/time/seconds, the year, month, etc.. are 1900 ... since they're not used)
I think something like this might work:
import time
import datetime
from time import mktime as mktime
#current time
now_date = datetime.datetime.now()
#time at 7am
today = datetime.date.today()
now_date2 = datetime.datetime(today.year, today.month, today.day, 7, 0, 0, 0)
#difference in minutes
(now_date - now_date2).days * 24 * 60

Converting between time formats

Is there a way to convert time from the year_month_day-hh_mm_ss to timestapm (in milliseconds since 1971) with DateUtils? or some other library..
thanks.
Have a look at the Python datetime and time modules.
from datetime import datetime
d = datetime.strptime("2017_03_16-14:08:10", "%Y_%m_%d-%H:%M:%S")
This will create a datetime object of d
Then use mktime from Python's time module to get your timestamp
import time
time.mktime(d.timetuple())*1000
The *1000 is required to convert from seconds to milliseconds.
Also, do you mean 1971 or the Unix epoch (Jan 01 1970)?
Try the arrow module found at the following URL: https://pypi.python.org/pypi/arrow
You can parse the time with strptime, then you can get the time since epoch time in milliseconds by using strftime to format only seconds. Multiply by 1000 to get milliseconds.
converted_time.strftime("%s") * 1000
You can use timedelta
from datetime import timedelta
year = timedelta(days=(2017-1971)*365)#number of days from 1971 to 2017
mili_sec = (year.total_seconds())*1000#you will get total_seconds just mulitply with 1000 to get milliseconds
OUTPUT
1450656000000.0
OR
You wanted difference from a particular date.Ex from 1971-01-01 to 2017-03-16-14:08:10
from datetime import datetime
new_day = datetime.strptime("2017_03_16-14:08:10", "%Y_%m_%d-%H:%M:%S")
old_day = datetime.strptime("1971_01_01-00:00:00", "%Y_%m_%d-%H:%M:%S")
diff_day_milliseconds = ((new_day - old_day).total_seconds())*1000
OUTPUT
1458137290000.0

how to shift a datetime object by 12 hours in python

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

Categories

Resources