I have some input data, with timestamps in the input file in the form of hours from the date time specified in the filename.

This is a bit useless, so I need to convert it to python datetime.datetime objects, and then put it in a numpy array. I could write a for loop, but I'd like to do something like:

```
numpy.arange(datetime.datetime(2000, 1,1), datetime.datetime(2000, 1,2), datetime.timedelta(hours=1))
```

which throws a TypeError.

Can this be done? I'm stuck with python 2.6 and numpy 1.6.1.

See NumPy Datetimes and Timedeltas. Basically, you can represent datetimes in NumPy using the `numpy.datetime64`

type, which permits you to do ranges of values.

For NumPy 1.6, which has a much less useful `datetime64`

type, you can use a suitable list comprehension to build the datetimes (see also Creating a range of dates in Python):

```
base = datetime.datetime(2000, 1, 1)
arr = numpy.array([base + datetime.timedelta(hours=i) for i in xrange(24)])
```

This produces

```
array([2000-01-01 00:00:00, 2000-01-01 01:00:00, 2000-01-01 02:00:00,
2000-01-01 03:00:00, 2000-01-01 04:00:00, 2000-01-01 05:00:00,
2000-01-01 06:00:00, 2000-01-01 07:00:00, 2000-01-01 08:00:00,
2000-01-01 09:00:00, 2000-01-01 10:00:00, 2000-01-01 11:00:00,
2000-01-01 12:00:00, 2000-01-01 13:00:00, 2000-01-01 14:00:00,
2000-01-01 15:00:00, 2000-01-01 16:00:00, 2000-01-01 17:00:00,
2000-01-01 18:00:00, 2000-01-01 19:00:00, 2000-01-01 20:00:00,
2000-01-01 21:00:00, 2000-01-01 22:00:00, 2000-01-01 23:00:00], dtype=object)
```

Note that @nneonneo solution can be simplified in

```
result = first_date + np.arange(24) * datetime.timedelta(hours=1)
```

thanks to NumPy array manipulations. The `result`

array has then a `dtype=object`

.

For more complex ranges, you might be interested in the `scikits.timeseries`

package (no longer maintained) or better, the `pandas`

package that reimplemented most of the ideas of `scikits.timeseries`

. Both packages support older versions of NumPy (1.5, 1.6...)

```
t = np.arange(datetime(1985,7,1), datetime(2015,7,1), timedelta(days=1)).astype(datetime)
```

The key point here is to use `astype(datetime)`

, otherwise the result will be `datetime64`

.

As noted in another answer, for Numpy > 1.7, you can use Numpy's built-in datetime capability. The examples in the Numpy documentation don't include using `np.arange`

with steps, so here's one:

`timearray = np.arange('2000-01-01', '2000-01-02',np.timedelta64(1,'h'), dtype='datetime64')`

Numpy sets the dtype of this result to `datetime64[h]`

. You can set this explicitly to some smaller unit of time with `dtype='datetime64[m]'`

.

In version 1.8.1 (and I expect earlier), trying to add an offset to that result array that is smaller than an hour will have no effect.

`timearray += np.timedelta64(10,'s')`

does not change`timearray`

`timearray2 = timearray + np.timedelta64(10,'s')`

will add 10 seconds to`timearray`

and converts the dtype of`timearray2`

to`datetime64[s]`

Similar Questions

In Python, how do I convert a datetime.datetime into the kind of float that I would get from the time.time function?

I cannot install numpy because it can't find python 2.7, althought I have installed python. I have message: Python version 2.7 required, which can't find in registry Do have a solve of my problem?

How can I convert a varchar field of the form YYYYMMDD to a datetime in T-SQL? Thank you.

I tried to build a structured array with a datetime coloumn import numpy as np na_trades = np.zeros(2, dtype = 'datetime64,i4') na_trades[0] = (np.datetime64('1970-01-01 00:00:00'),0) TypeError: Canno

i am using python with gtk, trying to make a simple text editor with tabs, i am still new, so i wonder how can i make the tabs closable and reordable ? it is much easier in qt, but i loved gtk more. t

How can I make an average between dates in MySQL? I am more interested in the time values, hours and minutes. On a table with: | date_one | datetime | | date_two | datetime | Doing a query like: SEL

I currently have the following snippet: #!/usr/bin/python # -*- coding: utf-8 -*- import numpy from numpy import linalg A = [[1,2,47,11],[3,2,8,15],[0,0,3,1],[0,0,8,1]] S = [[113,49,2,283],[-113,0,3,3

Let's say I have some simple data y = [[datetime.datetime( 2012,1,1,1,1), 2.1], [datetime.datetime( 2012,1,1,1,2), -3.1], [datetime.datetime( 2012,1,1,1,3), 0.1]] and I want a numpy record array corr

how will i fix this problem on python. here's my code: import time import datetime from time import mktime from datetime import datetime date = '20120814174530' date_to_strp = time.strptime(date, '%Y

I have a question. I am currently moving over from matlab to python and whilst I found it easy to adapt to numpy and scipy some parts are still a bit enigmatic ;) What I want to do is calculate data i

Sorry for this simple question. How do i calculate simple derivative for function y=x^2+1 using Numpy? UPDATE: let's say, i want the value of derivative at x=5

How do I convert a numpy.datetime64 object to a datetime.datetime (or Timestamp)? In the following code, I create a datetime, timestamp and datetime64 objects. import datetime import numpy as np impor

I'm working a lot with spyder and the object inspector, which I find pretty convenient as an instant help function. Some modules seem to profit very nicely from this function. For example a pretty bas

I want to see numpy datetime64 objects by my specified timezone. >>> import numpy as np >>> np.datetime64('2013-03-10T01:30:54') numpy.datetime64('2013-03-10T01:30:54+0400') >>

How can I make a vertical UIToolbar?

This question already has an answer here: Efficient & pythonic check for singular matrix 3 answers I am not sure whether python-numpy can help us decide whether a matrix is singular or not.

TLDR: The following code is run in the different databases, Oracle: select sysdate from dual SQLite select datetime('now') When doing Session.CreateSQLQuery(cmd).UniqueResult<DateTime>() the re

I am running PyLint on a Python project. PyLint makes many complaints about being unable to find numpy members. How can I avoid this while avoiding skipping membership checks. From the code: import nu

In order for me to run a python script as a build step in Jenkins I add the following to Execute windows batch command: C:\Python27\python.exe D:\jenkins\p4v\main\BuildHelpers\HelloTest.py Why do I

I can't figure it out, where did I go wrong? I got the following datetime string, and need to parse it to datetime: string timestr = 1/20/2014 12:05:16 AM And I trying to parse it like this: DateTi

I would like to store DateTime values using the datetime2 type in SQL Server CE 3.5. If this is possible, how would I change my entity data model? I've tried editing it manually and Visual Studio refu

How to increment the day in datetime? In python. for i in xrange(1,5) date=datetime.datetime(2003,8,i,12,4,5) print date But i need pass through years? Any ideas? Should be easyier way....

How can i make this list to appear when i click on options for my edittext. Or else do i have a option for creating this list with code or as xml.

I got a binary file, and one of record field stored some date infomation. The save program is written by VC++ and using the DATE type. How can read it into C#'s DateTime type ? BTW: I tried DateTime.F

Similar to How to import numpy in python shell, but with different errors and context. Now, on to the problem. I successfully installed numpy 1.7.0 with minor hassle, although I had to do some registr

if date_num_posts < datetime.datetime.today(): is always true even if it's the same day because it is comparing time. How can I check if a date is the same day as datetime.today()?

My apologies if this has been answered many times, but I just can't find a solution. Assume the following code: import numpy as np A,_,_ = np.meshgrid(np.arange(5),np.arange(7),np.arange(10)) B = (ra

My script make a while True: begin with the F4 pressed, but I want it to stop when the F2 is pressed, how can I do it? I'm trying this (using pyhook) but doesn't work... def onKeyboardEvent(event): if

How can I convert the following: 031413 05:53 AM into DATETIME format? Where this code: SELECT CONVERT(DATETIME, '031413 05:53 AM') gives me an error.

I am having trouble figuring out why I make a set from a NumPy array, Python swaps the order of elements: import numpy as np A = np.array([2]) B = np.array([2, 8]) setA = set(A) setB = set(B) In [6]:

sorry for bothering you again with my newbie problems in Python. I am trying to make a simple calculation (multiplication) in python using combobox and I don't know how. Below you will find what I hav

I am trying to plot a bunch of data points (many thousands) in Python using matplotlib so I need each marker to be very small and precise. How do I get the smallest most simple marker possible? I use

So I'm trying to use the numpy.ma.where to create an array for me, in the same way as the numpy.where function can. The where function broadcasts my column array then replaces some of the elements wit

how to check if a numpy datetime is between time1 and time2(without date). Say I have a series of datetime, i want to check its weekday, and whether it's between 13:00 and 13:30. For example 2014-03-0

This question already has an answer here: How can I create a directly-executable, cross-platform, GUI app using Python? 8 answers How to deploy Python to Windows users? 4 answers I've used

I can't see how to reveal the units for numpy.datetime64. Say: t=np.datetime64(123456789, 'ms' ) What's the method to tell me the units are 'ms'?

I have the following 2 arrays: k=arange(1,100) m=arange(1,100) Then how to append or combine them into an array with 2 columns and 99 rows?

how can i make payment using this URL https://api-3t.sandbox.paypal.com/nvp and is there any difference making request from this URL https://svcs.sandbox.paypal.com/AdaptivePayments and this URL https

I'm trying to learn python (in the process of installing numpy 1.8.0 in order to install BioPython), and am receiving the error numpy requires System Python 2.7 to install when I try to put numpy on

How can I run telnet command in the python GUI?

How can I make an integer negative in C#? abc = 5645307; // how to make abc -5645307 ?

I am just playing around with a particle simulator, I want to use matplotlib with python and numpy to make as realistic a simulator as possible as efficiently as possible (this is purely an exercise i

I have a Python datetime, d, and I want to get the number of hours since midnight as a floating point number. The best I've come up with is: h = ((((d.hour * 60) + d.minute) * 60) + d.second) / (60.0

I can't find NumPy for windows python 2.7 although I found an OS X version of it.

Simplified question Can I make Numpy agree with Matlab and Python's round? Matlab 2013a: >> round(-0.5) ans = -1 Python (using a Numpy array, or just a scalar, same result): >>> impor

How can I make a counter from 0 to 10 choosing the delay?

How can I check if a variable is a datetime type on php, please? I've tried this, but it seems doesn't work. public function setRegistrationDate ($registrationDate) { if (!is_date($registrationDate,

I have a string with the name myDateTime and the value 'datetime.datetime(2012, 11, 16, 3, 0)'. myDateTime = 'datetime.datetime(2012, 11, 16, 3, 0)' In Python, how can I get this string in the format

Is there a way to store datetime? So that I can calculate time difference between two datetimes and query with range of datetime. Also I want to indicate an exact time. ex) 12:00:00 01-Jan-2001 Should

I am playing with numpy and digging through documentation and I have come across some magic. Namely I am talking about numpy.where(): >>> x = np.arange(9.).reshape(3, 3) >>> np.where