This page demonstrates Python tips and tricks that I use in my everyday programming as an atmospheric science graduate student.
-Brian Blaylock

Tuesday, August 30, 2016

Dealing with python datetime arrays

Sometimes it's a pain that you can't perform datetime operations on each element of a numpy array. Here are a couple tipes

1. List of a range of datetime objects

The best way to make a list of datetime objects or numpy array is to use this tip:


which creates a list of datetime objects from today going back a day until it hits the number of days range limit. You can change the - to a + to increment one day in the future, or change the days argument to hours, etc.

2. Convert list of datetime strings to python datetime objects

When you read in date and time data from a file, it will often come in as a string. Often, you'll read these in as a list. To convert that list of strings to a list of python datetime objects do this:

3. Convert list of epoch times to python datetime objects


Alternatively, if the dates come in as a list of epoch times, use this...


4. Convert list of datetime strings to python datetime objects using a numpy vectorized function

This method is slightly appears to be slightly faster than method discussed in 2.


In the past I would create an empty array and append to it with a for loop like this...
but this method takes longer to compute, especially for long arrays.

2 comments:

  1. Point 4 was super helpful, thanks. I'd been looking for a loop-free solution to that everywhere!

    ReplyDelete
  2. More recently, I am using Pandas for nearly all my datetime lists and conversions
    pandas.to_datetime
    pandas.date_range
    pandas.to_timedelta

    ReplyDelete

Note: Only a member of this blog may post a comment.