I have the following problem I need to convert some datetime object to time_ns (present in time)
all I can find is to convert the now datetime to that fixed nanoseconds number (i understand that it is calculated from a fixed date in 1970)
import time
now = time.time_ns()
all I want is to convert some normal datetime object to that fixed nanoseconds number
from datetime import datetime
x = datetime(2022, 2, 22, 15, 41, 50)
i don't want to be restricted to only now dates. is there some function in the library that does that? for the moment i cannot find anything
thank you very much
Since python 3.3 datetime has a timestamp function. Make sure to replace the timezone, otherwise local timezone will being taken and if you want to have nanosecond number you can multiply the seconds number.
from datetime import datetime;
print(datetime(2022,2,22,15,41,50).replace(tzinfo=timezone.utc).timestamp()*10**9)
Related
I need help with converting time to a readable format. My time array (has 580 elements) is # of days since January 1st, 1900. How do I convert that to a normal time format (ie mm-dd-yyyy)?
For example, input time is 43,887 and output should read 02-27-2020 after adding it to Jan 1, 1900.
Thank you!
datetime.datetime and timedelta class can be helpful here.
from datetime import datetime, timedelta
def convert(inp, date1):
new_date = date1 + timedelta(inp)
return new_date.strftime("%m-%d-%Y")
date1 = datetime(1900, 1, 1)
print(convert(43887, date1))
You can use the datetime.datetime class can help you here. The following works, if those values are treated as integer days (you don't specify what they are).
from datetime import datetime
dt = datetime.fromordinal(43887)
dt.strftime('%d-%m-%Y')
I have a timestamp such 1474398821633L that I think is in utc. I want to compare it to datetime.datetime.now() to verify if it is expired.
I am using python 2.7
from datetime import datetime
timestamp = 1474398821633L
now = datetime.now()
if datetime.utcfromtimestamp(timestamp) < now:
print "timestamp expired"
However I got this error when trying to create a datetime object from the timestamp: ValueError: timestamp out of range for platform localtime()/gmtime() function
What can I do?
It looks like your timestamp is in milliseconds. Python uses timestamps in seconds:
>>> datetime.datetime.utcfromtimestamp(1474398821.633)
datetime.datetime(2016, 9, 20, 19, 13, 41, 633000)
In other words, you might need to divide your timestamp by 1000. in order to get it in the proper range.
Also, you'll probably want to compare datetime.utcnow() instead of datetime.now() to make sure that you're handling timezones correctly :-).
As #mgilson pointed out your input is likely "milliseconds", not "seconds since epoch".
Use time.time() instead of datetime.now():
import time
if time.time() > (timestamp_in_millis * 1e-3):
print("expired")
If you need datetime then use datetime.utcnow() instead of datetime.now(). Do not compare .now() that returns local time as a naive datetime object with utcfromtimestamp() that returns UTC time also as a naive datetime object (it is like comparing celsius and fahrenheit directly: you should convert to the same unit first).
from datetime import datetime
now = datetime.utcnow()
then = datetime.utcfromtimestamp(timestamp_in_millis * 1e-3)
if now > then:
print("expired")
See more details in Find if 24 hrs have passed between datetimes - Python.
I have a time series that I have pulled from a netCDF file and I'm trying to convert them to a datetime format. The format of the time series is in 'days since 1990-01-01 00:00:00 +10' (+10 being GMT: +10)
time = nc_data.variables['time'][:]
time_idx = 0 # first timestamp
print time[time_idx]
9465.0
My desired output is a datetime object like so (also GMT +10):
"2015-12-01 00:00:00"
I have tried converting this using the time module without much success although I believe I may be using wrong (I'm still a novice in python and programming).
import time
time_datetime = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(time[time_idx]*24*60*60))
Any advice appreciated,
Cheers!
The datetime module's timedelta is probably what you're looking for.
For example:
from datetime import date, timedelta
days = 9465 # This may work for floats in general, but using integers
# is more precise (e.g. days = int(9465.0))
start = date(1990,1,1) # This is the "days since" part
delta = timedelta(days) # Create a time delta object from the number of days
offset = start + delta # Add the specified number of days to 1990
print(offset) # >>> 2015-12-01
print(type(offset)) # >>> <class 'datetime.date'>
You can then use and/or manipulate the offset object, or convert it to a string representation however you see fit.
You can use the same format as for this date object as you do for your time_datetime:
print(offset.strftime('%Y-%m-%d %H:%M:%S'))
Output:
2015-12-01 00:00:00
Instead of using a date object, you could use a datetime object instead if, for example, you were later going to add hours/minutes/seconds/timezone offsets to it.
The code would stay the same as above with the exception of two lines:
# Here, you're importing datetime instead of date
from datetime import datetime, timedelta
# Here, you're creating a datetime object instead of a date object
start = datetime(1990,1,1) # This is the "days since" part
Note: Although you don't state it, but the other answer suggests you might be looking for timezone aware datetimes. If that's the case, dateutil is the way to go in Python 2 as the other answer suggests. In Python 3, you'd want to use the datetime module's tzinfo.
netCDF num2date is the correct function to use here:
import netCDF4
ncfile = netCDF4.Dataset('./foo.nc', 'r')
time = ncfile.variables['time'] # do not cast to numpy array yet
time_convert = netCDF4.num2date(time[:], time.units, time.calendar)
This will convert number of days since 1900-01-01 (i.e. the units of time) to python datetime objects. If time does not have a calendar attribute, you'll need to specify the calendar, or use the default of standard.
We can do this in a couple steps. First, we are going to use the dateutil library to handle our work. It will make some of this easier.
The first step is to get a datetime object from your string (1990-01-01 00:00:00 +10). We'll do that with the following code:
from datetime import datetime
from dateutil.relativedelta import relativedelta
import dateutil.parser
days_since = '1990-01-01 00:00:00 +10'
days_since_dt = dateutil.parser.parse(days_since)
Now, our days_since_dt will look like this:
datetime.datetime(1990, 1, 1, 0, 0, tzinfo=tzoffset(None, 36000))
We'll use that in our next step, of determining the new date. We'll use relativedelta in dateutils to handle this math.
new_date = days_since_dt + relativedelta(days=9465.0)
This will result in your value in new_date having a value of:
datetime.datetime(2015, 12, 1, 0, 0, tzinfo=tzoffset(None, 36000))
This method ensures that the answer you receive continues to be in GMT+10.
If I have a number representing a period I am interested in, for example the number 360 representing 360 minutes or 6 hours, how do I turn this into a datetime object such that I can perform the standard datetime object functions on it?
Similarly, if I have a datetime object in the format 00:30:00, representing 30 minutes, how do I turn that into a normal integer variable?
import datetime
t = datetime.timedelta(minutes=360)
This will create an object, t, that you can use with other datetime objects.
To answer the 2nd question you just edited in, you can use t.total_seconds() to return whatever your timedelta holds back into an integer in seconds. You'll have to do the conversion to minutes or hours manually though.
You may want to look at time deltas:
delta = datetime.timedelta(minutes=360)
If your time data is in '00:30:00' format then you should use strptime
>>> from datetime import datetime
>>> time = '00:30:00'
>>> datetime.strptime(time, '%H:%M:%S).time()
datetime.time(0, 30)
If your data is in 30 (integer) format
>>> from datetime import datetime, timedelta
>>> from time import strftime, gmtime
>>> minutes = timedelta(minutes=360)
>>> time = strftime('%H:%M:%S', gmtime(minutes.total_seconds()))
>>> datetime.strptime(time, '%H:%M:%S').time()
datetime.time(6, 0)
What is the best way to handle portions of a second in Python? The datetime library is excellent, but as far as I can tell it cannot handle any unit less than a second.
In the datetime module, the datetime, time, and timedelta classes all have the smallest resolution of microseconds:
>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> now
datetime.datetime(2009, 12, 4, 23, 3, 27, 343000)
>>> now.microsecond
343000
if you want to display a datetime with fractional seconds, just insert a decimal point and strip trailing zeros:
>>> now.strftime("%Y-%m-%d %H:%M:%S.%f").rstrip('0')
'2009-12-04 23:03:27.343'
the datetime and time classes only accept integer input and hours, minutes and seconds must be between 0 to 59 and microseconds must be between 0 and 999999. The timedelta class, however, will accept floating point values with fractions and do all the proper modulo arithmetic for you:
>>> span = timedelta(seconds=3662.567)
>>> span
datetime.timedelta(0, 3662, 567000)
The basic components of timedelta are day, second and microsecond (0, 3662, 567000 above), but the constructor will also accept milliseconds, hours and weeks. All inputs may be integers or floats (positive or negative). All arguments are converted to the base units and then normalized so that 0 <= seconds < 60 and 0 <= microseconds < 1000000.
You can add or subtract the span to a datetime or time instance or to another span. Fool around with it, you can probably easily come up with some functions or classes to do exaxtly what you want. You could probably do all your date/time processing using timedelta instances relative to some fixed datetime, say basetime = datetime(2000,1,1,0,0,0), then convert to a datetime or time instance for display or storage.
A different, non mentioned approach which I like:
from datetime import datetime
from time import sleep
t0 = datetime.now()
sleep(3)
t1 = datetime.now()
tdelta = t1 - t0
print(tdelta.total_seconds())
# will print something near (but not exactly 3)
# 3.0067
To get a better answer you'll need to specify your question further, but this should show at least how datetime can handle microseconds:
>>> from datetime import datetime
>>> t=datetime.now()
>>> t.microsecond
519943
NumPy 1.4 (in release candidate stage) has support for its own Date and DateArray objects. The one advantage is that it supports frequencies smaller than femtoseconds: http://projects.scipy.org/numpy/browser/trunk/doc/neps/datetime-proposal.rst
Otherwise I would go with the regular datetime subsecond frequencies.