Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6600077
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T18:34:29+00:00 2026-05-25T18:34:29+00:00

I have numpy ndarray which contains two columns: one is date, e.g. 2011-08-04, another

  • 0

I have numpy ndarray which contains two columns: one is date, e.g. 2011-08-04, another one is time, e.g. 19:00:00:081.

How can I combine them into one array of datetime objects? Currently, they’re strings in numpy array.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T18:34:29+00:00Added an answer on May 25, 2026 at 6:34 pm

    If the date and time string in the example.txt data file were given as one column with no separating whitespace, then genfromtxt could convert it into a datetime object like this:

    import numpy as np
    import datetime as dt
    def mkdate(text):
        return dt.datetime.strptime(text, '%Y-%m-%dT%H:%M:%S:%f')    
    data = np.genfromtxt(
        'example.txt',
        names=('data','num','date')+tuple('col{i}'.format(i=i) for i in range(19)),
        converters={'date':mkdate},
        dtype=None)
    

    Given example.txt as it is, you could form the desired numpy array with

    import numpy as np
    import datetime as dt
    import csv
    
    def mkdate(text):
        return dt.datetime.strptime(text, '%Y-%m-%d%H:%M:%S:%f')    
    
    def using_csv(fname):
        desc=([('data', '|S4'), ('num', '<i4'), ('date', '|O4')]+
              [('col{i}'.format(i=i), '<f8') for i in range(19)])
        with open(fname,'r') as f:
            reader=csv.reader(f,delimiter='\t')
            data=np.array([tuple(row[:2]+[mkdate(''.join(row[2:4]))]+row[4:])
                           for row in reader],
                          dtype=desc)
        # print(mc.report_memory())        
        return data
    

    Merging two columns in a numpy array can be a slow operation especially if the array is large. That’s because merging, like resizing, requires allocating memory for a new array, and copying data from the original array to the new one. So I think it is worth trying to form the correct numpy array directly, instead of in stages (by forming a partially correct array and merging two columns).


    By the way, I tested the above csv code versus merging two columns (below). Forming a single array from csv (above) was faster (and the memory usage was about the same):

    import matplotlib.cbook as mc
    import numpy as np
    import datetime as dt
    
    def using_genfromtxt(fname):
        data = np.genfromtxt(fname, dtype=None)
    
        orig_desc=data.dtype.descr
        view_desc=orig_desc[:2]+[('date','|S22')]+orig_desc[4:]
        new_desc=orig_desc[:2]+[('date','|O4')]+orig_desc[4:]
    
        newdata = np.empty(data.shape, dtype=new_desc)
        fields=data.dtype.names
        fields=fields[:2]+fields[4:]
        for field in fields:
            newdata[field] = data[field]
    
        newdata['date']=np.vectorize(mkdate)(data.view(view_desc)['date'])
        # print(mc.report_memory())
    
        return newdata  
    
    # using_csv('example4096.txt')
    # using_genfromtxt('example4096.txt')
    

    example4096.txt is the same as example.txt, duplicated 4096 times. It’s about 12K lines long.

    % python -mtimeit -s'import test' 'test.using_genfromtxt("example4096.txt")'
    10 loops, best of 3: 1.92 sec per loop
    
    % python -mtimeit -s'import test' 'test.using_csv("example4096.txt")'
    10 loops, best of 3: 982 msec per loop
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Suppose that I have two numpy arrays of the form x = [[1,2] [2,4]
So, I have three numpy arrays which store latitude, longitude, and some property value
I have a 2D numpy array of shape (N,2) which is holding N points
I have two Numpy record arrays that have exactly the same fields. What is
I have an array produced by numpy which looks as follows: [ 54.51399994 -12.10200024
I have two equally sized numpy arrays (they happen to be 48x365) where every
I will have to implement a convolution of two functions in Python, but SciPy/Numpy
I have two numpy arrays of different shapes, but with the same length (leading
Assuming I have a numpy array like: [1,2,3,4,5,6] and another array: [0,0,1,2,2,1] I want
How can I convert an ndarray to a matrix in numpy? I'm trying to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.