Dates & Times with datetime64
Reviewed & published by Brayan K
np.datetime64 is NumPy's native date-and-time type that stores each instant as an integer number of time units, letting whole arrays of dates take part in fast vectorized arithmetic.
Part of the free NumPy course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
You'll create dates and durations, choose units like 'D', 'h', and 's', do date arithmetic, generate date ranges with np.arange, convert to and from strings, and count business days with np.busday_count.
What You'll Learn in This Lesson
- Create dates with np.datetime64 and durations with timedelta64
- Choose a time unit: 'D', 'h', 's', and more
- Add and subtract dates to get timedeltas
- Generate a range of dates with np.arange
- Convert between datetime64 and strings
- Count working days with np.busday_count
1 Creating Dates and Durations
Build a date by passing an ISO string to np.datetime64("2026-06-17"). NumPy infers the unit from how much detail you give: a bare date gets day resolution 'D', while including a time gets finer units. A duration is a np.timedelta64(value, unit), for example five days or two hours.
import numpy as np
d = np.datetime64("2026-06-17") # day resolution
t = np.datetime64("2026-06-17T09:30") # minute resolution
five_days = np.timedelta64(5, "D")
two_hours = np.timedelta64(2, "h")import numpy as np
d = np.datetime64("2026-06-17")
print(d) # 2026-06-17
print(d.dtype) # datetime64[D]
t = np.datetime64("2026-06-17T09:30")
print(t) # 2026-06-17T09:30
print(t.dtype) # datetime64[m]
dur = np.timedelta64(5, "D")
print(dur) # 5 days
# ✅ Expected output:
# 2026-06-17
# datetime64[D]
# 2026-06-17T09:30
# datetime64[m]
# 5 days2 Date Arithmetic and Ranges
Subtracting two dates yields a timedelta64 — the gap between them. Adding a timedelta to a date shifts it. And because dates are integers internally, np.arange(start, stop, step) works directly on them to build an evenly spaced range of dates, stepping by whatever unit you provide.
start = np.datetime64("2026-01-01")
end = np.datetime64("2026-01-08")
end - start # 7 days (a timedelta64)
start + np.timedelta64(10, "D") # 2026-01-11
np.arange("2026-01", "2026-04", dtype="datetime64[M]")
# ['2026-01' '2026-02' '2026-03'] (monthly)import numpy as np
start = np.datetime64("2026-01-01")
end = np.datetime64("2026-01-08")
# Subtract dates -> a duration
print(end - start) # 7 days
# Add a duration to shift a date
print(start + np.timedelta64(10, "D")) # 2026-01-11
# A range of daily dates
days = np.arange("2026-01-01", "2026-01-06", dtype="datetime64[D]")
print(days)
# ['2026-01-01' '2026-01-02' '2026-01-03' '2026-01-04' '2026-01-05']
# Vectorized: how many days has each date been since the start?
print((days - start).astype(int)) # [0 1 2 3 4]
# ✅ Expected output:
# 7 days
# 2026-01-11
# ['2026-01-01' '2026-01-02' '2026-01-03' '2026-01-04' '2026-01-05']
# [0 1 2 3 4]3 Strings, Units, and Business Days
Convert a datetime64 to a string with np.datetime_as_string, and parse strings back by constructing np.datetime64 or using .astype. You can also change resolution by casting between units. Finally, np.busday_count(start, end) counts Monday-to-Friday days in the half-open range, ignoring weekends.
d = np.datetime64("2026-06-17")
np.datetime_as_string(d) # '2026-06-17'
d.astype("datetime64[M]") # 2026-06 (cast to month resolution)
np.busday_count("2026-06-15", "2026-06-22") # 5 weekdaysimport numpy as np
d = np.datetime64("2026-06-17")
# datetime64 -> string
print(np.datetime_as_string(d)) # 2026-06-17
# Cast down to month resolution
print(d.astype("datetime64[M]")) # 2026-06
# Parse an array of strings into dates
dates = np.array(["2026-03-01", "2026-03-15"], dtype="datetime64[D]")
print(dates)
# ['2026-03-01' '2026-03-15']
# Count weekdays (Mon-Fri) in a half-open range
print(np.busday_count("2026-06-15", "2026-06-22")) # 5
# ✅ Expected output:
# 2026-06-17
# 2026-06
# ['2026-03-01' '2026-03-15']
# 5🎯 YOUR TURN: Fill in the Blank
Shift a launch date forward by 30 days by filling in the unit code for days.
import numpy as np
launch = np.datetime64("2026-09-01")
# Add 30 DAYS. Fill in the unit code for days.
deadline = launch + np.timedelta64(30, "___")
print(deadline)
# Expected output:
# 2026-10-01Answer: D for days. Other unit codes include 'h' hours, 'm' minutes, and 's' seconds.
! Common Errors (And How to Fix Them)
❌ Adding a plain int to a date
A bare number has no unit, so NumPy cannot tell days from seconds:
np.datetime64("2026-01-01") + 5 # works but assumes the date's unit, easy to misread✅ Fix: be explicit with a timedelta64:
np.datetime64("2026-01-01") + np.timedelta64(5, "D")❌ busday_count off by one at the end
The range is half-open, so the end date itself is not counted.
✅ Fix: if you want the end day included, add one day to the stop date before counting.
❌ Surprising results when mixing units
Comparing a datetime64[D] with a datetime64[s] casts to the finer unit, which can confuse equality checks.
✅ Fix: cast both to the same unit with .astype("datetime64[D]") before comparing.
🎯 Mini Challenge: Project Timeline
Given a start date and a list of task durations in days, compute each task's end date and the total weekday span.
import numpy as np
start = np.datetime64("2026-06-01")
durations = np.array([3, 5, 2], dtype="timedelta64[D]")
# Cumulative end dates: start + running total of durations
ends = start + np.cumsum(durations)
print(ends)
# ['2026-06-04' '2026-06-09' '2026-06-11']
# Total calendar days spanned
total = durations.sum()
print("Total days:", total) # Total days: 10 days
# Weekdays from project start to the final end date
weekdays = np.busday_count(start, ends[-1])
print("Weekdays until finish:", weekdays) # Weekdays until finish: 8
# ✅ Expected output:
# ['2026-06-04' '2026-06-09' '2026-06-11']
# Total days: 10 days
# Weekdays until finish: 8❓ Frequently Asked Questions
Lesson complete — NumPy can keep time!
You can create dates and durations, pick a unit, do vectorized date arithmetic, build date ranges with np.arange, convert to and from strings, and count weekdays with np.busday_count.
Practice quiz
What does np.datetime64('2026-01-08') - np.datetime64('2026-01-01') return?
- 8 days
- 7 days
- 1 days
- 0 days
Answer: 7 days. Subtracting two dates gives a timedelta64; Jan 8 minus Jan 1 is 7 days.
What is the dtype of np.datetime64('2026-06-17')?
- datetime64[Y]
- datetime64[h]
- datetime64[D]
- datetime64[s]
Answer: datetime64[D]. A bare date with no time gets day resolution, datetime64[D].
How does NumPy store a datetime64 value internally?
- As a formatted string
- As a Python datetime object
- As an integer count of its unit since 1970-01-01
- As a float number of seconds
Answer: As an integer count of its unit since 1970-01-01. It is an integer count of its unit since the epoch 1970-01-01, which makes arithmetic fast.
What does np.timedelta64(5, 'D') represent?
- A duration of 5 days
- The date 2005
- 5 hours
- May 1970
Answer: A duration of 5 days. timedelta64(value, unit) is a duration; 'D' is the day unit, so this is 5 days.
What does np.busday_count('2026-06-15', '2026-06-22') return?
- 7
- 6
- 4
- 5
Answer: 5. It counts Mon-Fri in the half-open range; that week has 5 weekdays.
Which unit code means hours?
- 'h'
- 'H'
- 'hr'
- 'hour'
Answer: 'h'. NumPy uses lowercase 'h' for hours; 'm' is minutes and 's' is seconds.
Is the range for np.busday_count(a, b) inclusive of b?
- Yes, b is always counted
- No, the range is half-open and excludes b
- Only if b is a weekday
- Only if b is a weekend
Answer: No, the range is half-open and excludes b. Like Python's range, it includes a but excludes b.
What does np.datetime64('2026-06-17').astype('datetime64[M]') give?
- 2026-06-17
- 2026-06
- 2026
- 06-17
Answer: 2026-06. Casting to month resolution drops the day, leaving 2026-06.
How do you add 30 days to a date safely?
- date + 30
- date + '30D'
- date + np.timedelta64(30, 'D')
- date.add(30)
Answer: date + np.timedelta64(30, 'D'). A timedelta64 with an explicit unit makes the intent clear and unambiguous.
What does np.timedelta64(2, 'D') + np.timedelta64(3, 'D') equal?
- 6 days
- 5 days
- 1 days
- 23 days
Answer: 5 days. Durations with the same unit add directly: 2 + 3 = 5 days.
Continue this course
- Previous: Transposing & Swapping Axes
- Next: Polynomials: polyfit & poly1d — Fit and evaluate polynomials with polyfit, poly1d, polyval, and roots
- Quick reference: NumPy cheat sheet
Frequently asked questions
What is np.datetime64 and how is it different from Python's datetime?
np.datetime64 is NumPy's own 64-bit date and time type that stores an instant as an integer count of a chosen unit (days, hours, seconds, and so on) since the epoch 1970-01-01. Unlike Python's datetime, it lives inside NumPy arrays so you can hold thousands of dates in one contiguous array and do vectorized arithmetic on all of them at once.
What is a timedelta64 and how do I get one?
np.timedelta64 represents a duration, such as 5 days or 3 hours. Subtracting two datetime64 values produces a timedelta64, and you can add a timedelta64 to a datetime64 to shift it. You build one directly with np.timedelta64(5, 'D') for five days, where the second argument is the unit code.
What do the unit codes like 'D', 'h', and 's' mean?
They set the resolution of a datetime64 or timedelta64: 'Y' year, 'M' month, 'W' week, 'D' day, 'h' hour, 'm' minute, and 's' second, plus finer units like 'ms' and 'us'. The unit controls both precision and the size of one arithmetic step, so np.arange over dates with a 'D' unit steps one day at a time.
How do I count only working days between two dates?
np.busday_count(start, end) counts the business days (Monday to Friday by default) in the half-open interval from start up to but not including end. It is handy for things like SLA timers or delivery estimates where weekends should not count, and you can pass a custom weekmask or holiday list to refine it.