🔍 Code Extractor

function cftime_to_timestamp

Maturity: 51

Converts cftime datetime objects (or arrays) to timestamps since Unix epoch (1970-01-01 00:00:00) in specified time units, defaulting to microseconds.

File:
/tf/active/vicechatdev/patches/util.py
Lines:
2156 - 2178
Complexity:
moderate

Purpose

This function bridges non-standard calendar systems (Julian, no-leap, etc.) used in climate science with standard Gregorian timestamps for visualization and analysis tools like Bokeh. It normalizes cftime datetime objects to standard calendar timestamps, enabling interoperability with tools that expect standard datetime representations. Note that this conversion may introduce artifacts for dates that don't exist in the original calendar system.

Source Code

def cftime_to_timestamp(date, time_unit='us'):
    """Converts cftime to timestamp since epoch in milliseconds

    Non-standard calendars (e.g. Julian or no leap calendars)
    are converted to standard Gregorian calendar. This can cause
    extra space to be added for dates that don't exist in the original
    calendar. In order to handle these dates correctly a custom bokeh
    model with support for other calendars would have to be defined.

    Args:
        date: cftime datetime object (or array)

    Returns:
        time_unit since 1970-01-01 00:00:00
    """
    import cftime
    if time_unit == 'us':
        tscale = 1
    else:
        tscale = (np.timedelta64(1, 'us')/np.timedelta64(1, time_unit))

    return cftime.date2num(date,'microseconds since 1970-01-01 00:00:00',
                           calendar='standard')*tscale

Parameters

Name Type Default Kind
date - - positional_or_keyword
time_unit - 'us' positional_or_keyword

Parameter Details

date: A cftime datetime object or array of cftime datetime objects representing dates in potentially non-standard calendars (e.g., Julian, 360-day, no-leap calendars). Can be a single object or numpy array of objects.

time_unit: String specifying the time unit for the output timestamp. Defaults to 'us' (microseconds). Other valid values include standard numpy timedelta units like 'ms' (milliseconds), 's' (seconds), 'ns' (nanoseconds), etc. The function scales the output accordingly.

Return Value

Returns a numeric value or numpy array representing the number of time_unit intervals since the Unix epoch (1970-01-01 00:00:00). For default 'us', returns microseconds since epoch. The return type matches the input: scalar for single date, array for array input. Values are in the standard Gregorian calendar regardless of input calendar type.

Dependencies

  • cftime
  • numpy

Required Imports

import cftime
import numpy as np

Usage Example

import cftime
import numpy as np

# Single cftime datetime object
date = cftime.DatetimeNoLeap(2000, 3, 1, 12, 0, 0)
timestamp_us = cftime_to_timestamp(date, time_unit='us')
print(f"Microseconds since epoch: {timestamp_us}")

# Array of cftime objects
dates = [cftime.DatetimeNoLeap(2000, 1, 1), cftime.DatetimeNoLeap(2000, 6, 1)]
timestamps = cftime_to_timestamp(dates, time_unit='ms')
print(f"Milliseconds since epoch: {timestamps}")

# Using different time units
timestamp_s = cftime_to_timestamp(date, time_unit='s')
print(f"Seconds since epoch: {timestamp_s}")

Best Practices

  • Be aware that converting from non-standard calendars (Julian, 360-day, no-leap) to standard Gregorian may introduce dates that didn't exist in the original calendar system
  • When working with climate model data that uses non-standard calendars, document the calendar conversion to avoid confusion about date accuracy
  • For visualization in Bokeh or similar tools, this conversion is necessary but may require additional handling for calendar-specific edge cases
  • The default time_unit='us' (microseconds) provides high precision but may result in very large numbers; consider using 'ms' or 's' for more readable values
  • Ensure input dates are valid cftime objects; the function expects cftime.datetime instances, not standard Python datetime objects
  • The function uses cftime.date2num internally with 'standard' calendar, which means all output is normalized to proleptic Gregorian calendar

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function dt_to_int 61.0% similar

    Converts various datetime types (pandas, numpy, cftime, Python datetime) to an integer timestamp with a specified time unit.

    From: /tf/active/vicechatdev/patches/util.py
  • function format_datetime_v1 50.6% similar

    Converts an ISO format datetime string into a human-readable UTC datetime string formatted as 'YYYY-MM-DD HH:MM:SS UTC'.

    From: /tf/active/vicechatdev/SPFCsync/dry_run_test.py
  • function parse_datetime_v1 48.4% similar

    Converts various date representations (string, integer, pandas Timestamp) into a numpy datetime64 object using pandas datetime parsing capabilities.

    From: /tf/active/vicechatdev/patches/util.py
  • function dt64_to_dt 48.3% similar

    Converts a NumPy datetime64 object to a Python datetime.datetime object by calculating seconds since Unix epoch.

    From: /tf/active/vicechatdev/patches/util.py
  • function format_datetime 47.9% similar

    Formats a datetime object into a standardized string representation for display purposes, returning an empty string if the input is None.

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
← Back to Browse