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?
Related
I have a recording with the start time (t0) and length of the recording (N). How do I create a time series vector (ts) in python for every 10s increments?
For example:
t0 = 2017-06-12T11:05:10.00
N=1000
So there should be an array of 100 (N/10)values such that:
ts = [2017-06-12T11:05:10.00, 2017-06-12T11:05:20.00,2017-06-12T11:05:30.00 and so on...]
You can use the datetime module of Python.
First you need to convert your string into a date with dateteime.strptime:
t0 = datetime.datetime.strptime("2017-06-12T11:05:10.00", "%Y-%m-%dT%H:%M:%S.00")
where the "%Y-%m-%dT%H:%M:%S.00" part is the description of your string format (see documentation)
Then you can increment a datetime object by adding a timedelta to it. Build a sequence like this:
delta = datetime.timedelta(seconds=10)
ts = [t0 + i*delta for i in range(N)]
You can also recover dates as strings by using datetime.strftime with a similar syntax to strptime.
The whole thing would look like
from datetime import datetime, timedelta
date_format = "%Y-%m-%dT%H:%M:%S.00"
t0 = datetime.strptime("2017-06-12T11:05:10.00", date_format)
delta = timedelta(seconds=10)
ts = [datetime.strftime(t0 + i * delta, date_format) for i in range(100)]
import datetime
import numpy as np
t0=datetime.datetime(2017, 6, 12, 11, 5, 10)
dt=datetime.timedelta(seconds=10)
ts=np.arange(100)*dt+t0
There might be some easier way. I've never tried to find one. But this is how I do it.
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)
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)
I'a m trying to extract only time (Hour:Minute) from datetime field
Example:
today_with_hour = fields.Datetime(
string=u'hora',
default=fields.Datetime.now,
)
I would like to know how get only hour from today_with_hour in format
17:10:20
This is one way to extract:
from datetime import datetime
now = datetime.now()
print(str(now.hour)+':'+str(now.minute)+':'+str(now.second))
This may be better way to do it
You can use strftime
Example:
from datetime import datetime
datetime.now().strftime("%H:%M:%S")
In your case you can follow like this:
from datetime import datetime
datetime.strptime('20/06/2019 17:28:52', "%d/%m/%Y %H:%M:%S").time()
Output will be:
17:28:52
Better way to do is by using strftime().
dt = datetime.strptime('20/06/2019 17:28:52', "%d/%m/%Y %H:%M:%S")
dt.strftime("%H:%M:%S")
output:
17:28:52
To get the current time from the datetime.now()
datetime.datetime.now().time().strftime("%H:%M:%S")
O/P:
'11:16:17'
if you want to get the time with milliseconds also, use isoformat()
datetime.datetime.now().time().isoformat()
O/P:
'11:20:34.978272'
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