Convert local time to UNIX - python

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

Related

python datetime calculation not trimming to milliseconds

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)

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)

How to get the milliseconds of the beginning of today?

I can get current time in milliseconds as follows:
import time
timestamp = int(time.time()*1000.0)
However, how can I get the milliseconds of the beginning of today, e.g. 09/09/2018 00:00 ?
import pandas as pd
import datetime
int(pd.to_datetime(datetime.datetime.now().date()).value / 1000000)
# Outputs: 1536451200000
I hope this works to get the required start of the date's time in milliseconds in Python 3
from datetime import datetime
dt_obj = datetime.strptime('09.09.2019 00:00',
'%d.%m.%Y %H:%M')
millisec = dt_obj.timestamp() * 1000
print(millisec)
Output>> 1568001600000.0

Write a python script to generate a timestamp ( unix epoch value) each day at a give time

I want to write a small python which needs to generate a simple precise timestamp each day ( the script will be run each day) at a particular hour say 1pm. I wrote something like this:
from datetime import datetime
now = datetime.utcnow() # Current time
then = datetime(1970,1,1) # 0 epoch time
ts = now - then
ts = ts.days * 24 * 3600 + ts.seconds
print ts
This is good, but i want to pass now for the time_field that i on daily basis. How do I do this?
You can use the time.mktime function:
>>> import datetime
>>> import time
>>> dt = datetime.datetime.today().replace(hour=13, minute=0, second=0, microsecond=0)
>>> print(dt)
2016-04-06 13:00:00
>>> time.mktime(dt.timetuple())
1459944000.0
If you need to be timezone-aware, use a timezone-aware datetime's utctimetuple method and the time.gmtime function.
(edited to show how to create datetime.datetime for a specific time)
date command in shell gives us epoch time also.
date +%s
So write your python script as
import subprocess
p = subprocess.Popen(['date', '+%s'], stdout=subprocess.PIPE,stderr=subprocess.PIPE)
out, err = p.communicate()
print out
and then call it daily with the same logic you are using now.
To generate a POSIX timestamp that corresponds to 1pm:
#!/usr/bin/env python3
from datetime import datetime
import tzlocal # $ pip install tzlocal
local_timezone = tzlocal.get_localzone()
now = datetime.now(local_timezone)
one_pm = local_timezone.localize(datetime(now.year, now.month, now.day, 13), # 1pm
is_dst=None) # assert that there is no DST transition at 1pm
posix_time = one_pm.timestamp()
If there is no datetime.timestamp() method on your Python version then it is easy to implement it for a timezone-aware datetime object such as one_pm:
def posix_timestamp(aware, epoch=datetime(1970, 1, 1)):
utc = aware.replace(tzinfo=None) - aware.utcoffset() # convert to utc
return (utc - epoch).total_seconds()
If there is no DST transition at 1pm and mktime() uses a correct timezone definition on a given platform then to get Unix time that corresponds to 1pm:
#!/usr/bin/env python
import time
unix_time = time.mktime(time.localtime()[:3] + (13, 0, 0) + (-1,)*3)

How to convert ticks to datetime in Python?

How to convert ticks to datetime in Python?
I am trying to convert 52707330000 to 1 hour and 27 minutes and 50 seconds.
Somehow it works here - http://tickstodatetime.com/. I tried inspecting the element but I don't understand javascript.
The following will convert the ticks to a Python datetime object (from now) using datetime's timedelta.
import datetime
ticks = 52707330000
converted_ticks = datetime.datetime.now() + datetime.timedelta(microseconds = ticks/10)
Then something like:
converted_ticks.strftime("%Y-%m-%d %H:%M:%S") // '2015-08-07 14:17:48'
Hope this helps!
EDIT: Using just datetime.timedelta(microseconds = ticks/10) will give you the time, not relative to "now".
To get the same time as on the web-site:
#!/usr/bin/env python
from __future__ import division
from datetime import datetime, timedelta
ticks = 52707330000
dt = datetime(1, 1, 1) + timedelta(microseconds=ticks/10)
print(dt.isoformat() + "Z")
# -> 0001-01-01T01:27:50.733000Z
You could just use:
from datetime import datetime
timestamp = 52707330000
your_date = datetime.fromtimestamp(timestamp)
or not?

Categories

Resources