search
Search
Publish
menu
menu search toc more_vert
Robocat
Guest 0reps
Thanks for the thanks!
close
chevron_left Documentation
Method argpartition
NumPy Random Generator4 topics
Method choiceMethod dotMethod finfoMethod histogramMethod iinfoMethod maxMethod meanMethod placeMethod rootsMethod seedMethod uniformMethod viewMethod zerosMethod sumObject busdaycalendarMethod is_busdayProperty dtypeMethod uniqueMethod loadtxtMethod vsplitMethod fliplrMethod setdiff1dMethod msortMethod argsortMethod lexsortMethod aroundMethod nanmaxMethod nanminMethod nanargmaxMethod nanargminMethod argmaxMethod argminProperty itemsizeMethod spacingMethod fixMethod ceilMethod diffProperty flatProperty realProperty baseMethod flipMethod deleteMethod amaxMethod aminMethod logical_xorMethod logical_orMethod logical_notMethod logical_andMethod logaddexpMethod logaddexp2Method logspaceMethod not_equalMethod equalMethod greater_equalMethod lessMethod less_equalMethod remainderMethod modMethod emptyMethod greaterMethod isfiniteMethod busday_countMethod repeatMethod varMethod random_sampleMethod randomMethod signMethod stdMethod absoluteMethod absMethod sortMethod randintMethod isrealMethod linspaceMethod gradientMethod allMethod sampleProperty TProperty imagMethod covMethod insertMethod logMethod log1pMethod exp2Method expm1Method expMethod arccosMethod cosMethod arcsinMethod sinMethod tanMethod fromiterMethod trim_zerosMethod diagflatMethod savetxtMethod count_nonzeroProperty sizeProperty shapeMethod reshapeMethod resizeMethod triuMethod trilMethod eyeMethod arangeMethod fill_diagonalMethod tileMethod saveMethod transposeMethod swapaxesMethod meshgridProperty mgridMethod rot90Method log2Method radiansMethod deg2radMethod rad2degMethod degreesMethod log10Method appendMethod cumprodProperty nbytesMethod tostringProperty dataMethod modfMethod fmodMethod tolistMethod datetime_as_stringMethod datetime_dataMethod array_splitMethod itemsetMethod floorMethod put_along_axisMethod cumsumMethod bincountMethod putMethod putmaskMethod takeMethod hypotMethod sqrtMethod squareMethod floor_divideMethod triMethod signbitMethod flattenMethod ravelMethod rollMethod isrealobjMethod diagMethod diagonalMethod quantileMethod onesMethod iscomplexobjMethod iscomplexMethod isscalarMethod divmodMethod isnatMethod percentileMethod isnanMethod divideMethod addMethod reciprocalMethod positiveMethod subtractMethod medianMethod isneginfMethod isposinfMethod float_powerMethod powerMethod negativeMethod maximumMethod averageMethod isinfMethod multiplyMethod busday_offsetMethod identityMethod interpMethod squeezeMethod get_printoptionsMethod savez_compressedMethod savezMethod loadMethod asfarrayMethod clipMethod arrayMethod array_equivMethod array_equalMethod frombufferMethod set_string_functionMethod matmulMethod genfromtxtMethod fromfunctionMethod asscalarMethod searchsortedMethod full_likeMethod fullMethod shares_memoryMethod ptpMethod digitizeMethod argwhereMethod geomspaceMethod zeros_likeMethod fabsMethod flatnonzeroMethod vstackMethod dstackMethod fromstringMethod tobytesMethod expand_dimsMethod ranfMethod arctanMethod itemMethod extractMethod compressMethod chooseMethod asarrayMethod asmatrixMethod allcloseMethod iscloseMethod anyMethod corrcoefMethod truncMethod prodMethod crossMethod true_divideMethod hsplitMethod splitMethod rintMethod ediff1dMethod lcmMethod gcdMethod cbrtMethod flipudProperty ndimMethod array2stringMethod set_printoptionsMethod whereMethod hstack
Char32 topics
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
help Ask a question
Share on Twitter
search
keyboard_voice
close
Searching Tips
Search for a recipe: "Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to
A
A
share
thumb_up_alt
bookmark
arrow_backShare
Twitter
Facebook
chevron_left Documentation
Method argpartition
NumPy Random Generator4 topics
Method choiceMethod dotMethod finfoMethod histogramMethod iinfoMethod maxMethod meanMethod placeMethod rootsMethod seedMethod uniformMethod viewMethod zerosMethod sumObject busdaycalendarMethod is_busdayProperty dtypeMethod uniqueMethod loadtxtMethod vsplitMethod fliplrMethod setdiff1dMethod msortMethod argsortMethod lexsortMethod aroundMethod nanmaxMethod nanminMethod nanargmaxMethod nanargminMethod argmaxMethod argminProperty itemsizeMethod spacingMethod fixMethod ceilMethod diffProperty flatProperty realProperty baseMethod flipMethod deleteMethod amaxMethod aminMethod logical_xorMethod logical_orMethod logical_notMethod logical_andMethod logaddexpMethod logaddexp2Method logspaceMethod not_equalMethod equalMethod greater_equalMethod lessMethod less_equalMethod remainderMethod modMethod emptyMethod greaterMethod isfiniteMethod busday_countMethod repeatMethod varMethod random_sampleMethod randomMethod signMethod stdMethod absoluteMethod absMethod sortMethod randintMethod isrealMethod linspaceMethod gradientMethod allMethod sampleProperty TProperty imagMethod covMethod insertMethod logMethod log1pMethod exp2Method expm1Method expMethod arccosMethod cosMethod arcsinMethod sinMethod tanMethod fromiterMethod trim_zerosMethod diagflatMethod savetxtMethod count_nonzeroProperty sizeProperty shapeMethod reshapeMethod resizeMethod triuMethod trilMethod eyeMethod arangeMethod fill_diagonalMethod tileMethod saveMethod transposeMethod swapaxesMethod meshgridProperty mgridMethod rot90Method log2Method radiansMethod deg2radMethod rad2degMethod degreesMethod log10Method appendMethod cumprodProperty nbytesMethod tostringProperty dataMethod modfMethod fmodMethod tolistMethod datetime_as_stringMethod datetime_dataMethod array_splitMethod itemsetMethod floorMethod put_along_axisMethod cumsumMethod bincountMethod putMethod putmaskMethod takeMethod hypotMethod sqrtMethod squareMethod floor_divideMethod triMethod signbitMethod flattenMethod ravelMethod rollMethod isrealobjMethod diagMethod diagonalMethod quantileMethod onesMethod iscomplexobjMethod iscomplexMethod isscalarMethod divmodMethod isnatMethod percentileMethod isnanMethod divideMethod addMethod reciprocalMethod positiveMethod subtractMethod medianMethod isneginfMethod isposinfMethod float_powerMethod powerMethod negativeMethod maximumMethod averageMethod isinfMethod multiplyMethod busday_offsetMethod identityMethod interpMethod squeezeMethod get_printoptionsMethod savez_compressedMethod savezMethod loadMethod asfarrayMethod clipMethod arrayMethod array_equivMethod array_equalMethod frombufferMethod set_string_functionMethod matmulMethod genfromtxtMethod fromfunctionMethod asscalarMethod searchsortedMethod full_likeMethod fullMethod shares_memoryMethod ptpMethod digitizeMethod argwhereMethod geomspaceMethod zeros_likeMethod fabsMethod flatnonzeroMethod vstackMethod dstackMethod fromstringMethod tobytesMethod expand_dimsMethod ranfMethod arctanMethod itemMethod extractMethod compressMethod chooseMethod asarrayMethod asmatrixMethod allcloseMethod iscloseMethod anyMethod corrcoefMethod truncMethod prodMethod crossMethod true_divideMethod hsplitMethod splitMethod rintMethod ediff1dMethod lcmMethod gcdMethod cbrtMethod flipudProperty ndimMethod array2stringMethod set_printoptionsMethod whereMethod hstack
Char32 topics
thumb_up
0
thumb_down
0
chat_bubble_outline
0
auto_stories new
settings

NumPy | datetime_as_string method

Programming
chevron_right
Python
chevron_right
NumPy
chevron_right
Documentation
schedule Mar 10, 2022
Last updated
local_offer PythonNumPy
Tags

NumPy's datetime_as_string(~) method converts an array of datetimes into an array of strings, and offers a myriad of ways for formatting.

Parameters

1. arr | array-like

An array of datetimes.

2. unit | None or string | optional

The format of the resulting strings. The allowed values are as follows:

Unit

Description

None

The unit becomes the lowest unit in the input array. For instance, if you had ["2020-12-25", "2020-12"], the lowest unit here would be days, and so we'll end up with ["2020-12-25", "2020-12-01"].

"auto"

The unit is equivalent to "D", that is, days. For instance, strings will all be of the form "2020-12-25".

Dateunit

Can be any of "Y" (years), "M" (months), "W" (weeks), "D" (days), "h" (hours), "m" (minutes), "s" (seconds), and "ms" (milliseconds).

Note that for dates that lack a certain unit, the default value of unit one is used. For instance, specifying a unit of "D" (i.e. days) would convert datetimes like "2020-12" to "2020-12-01".

By default, unit=None.

3. timezone | string | optional

The timezone to use. The allowed values are as follows:

Timezone

Description

naive

A "naive" timezone is one that unaware of timezone - it's just a plain datetime without absolutely any context of locality.

UTC

The Coordinated Universal Time.

local

Takes into account the timezone of your geographical location.

By default, timezone="naive". See examples below for clarification.

4. casting | string | optional

The casting rules to abide by. The official documentation does not provide any explanation on the specifics of the rules, so here we will attempt to introduce some of the main rules at a basic level.

Rule

Description

no

Throws an error whenever any type of casting is performed.

safe

Throws an error when you cast to a less specific unit (e.g. from days to weeks).

unsafe

Allows for any type of casting. This is the opposite of the "no" rule.

For those who have more insights, we'd love to talk with you!

Return value

A NumPy array of strings that represent the input datetimes.

Examples

Basic usage

datetimes = [np.datetime64("2020-05-30"), np.datetime64("2020-12-25")]
np.datetime_as_string(datetimes)
array(['2020-05-30', '2020-12-25'], dtype='<U28')

Changing the units

None

datetimes = [np.datetime64("2020-05"), np.datetime64("2020-12")]
np.datetime_as_string(datetimes, unit=None)
array(['2020-05', '2020-12'], dtype='<U25')

auto

datetimes = [np.datetime64("2020-05"), np.datetime64("2020-12")]
np.datetime_as_string(datetimes, unit="auto")
array(['2020-05-01', '2020-12-01'], dtype='<U62')

Notice how the resulting strings have days, that is, unit="auto" is identical to unit="D" (days).

Months

datetimes = [np.datetime64("2020-05-30"), np.datetime64("2020-12-25")]
np.datetime_as_string(datetimes, unit="M")
array(['2020-05', '2020-12'], dtype='<U25')

Changing the timezone

Naive

datetimes = [np.datetime64("2020-12-25T03:30"), np.datetime64("2020-12-06T02:50")]
np.datetime_as_string(datetimes, timezone="naive")
array(['2020-12-25T03:30', '2020-12-06T02:50'], dtype='<U35')

UTC

datetimes = [np.datetime64("2020-12-25T03:30"), np.datetime64("2020-12-06T02:50")]
np.datetime_as_string(datetimes, timezone="UTC")
array(['2020-12-25T03:30Z', '2020-12-06T02:50Z'], dtype='<U35')

Notice how we have Z at the end, indicating that the timezone is UTC.

local

datetimes = [np.datetime64("2020-12-25T03:30"), np.datetime64("2020-12-06T02:50")]
np.datetime_as_string(datetimes, timezone="local")
array(['2020-12-25T11:30+0800', '2020-12-06T10:50+0800'], dtype='<U39')

Notice how we have +0800 at the end, which means that my current location is 8 hours ahead of UTC.

Casting rules

no

datetimes = [np.datetime64("2020-05-05")]
np.datetime_as_string(datetimes, unit="M", casting="no")
TypeError: Cannot create a datetime string as units 'M' from a NumPy datetime with units 'D' according to the rule 'no'

This throws an error because the "no" rule does not allow for any form of casting.

safe

datetimes = [np.datetime64("2020-05-05")]
np.datetime_as_string(datetimes, unit="M", casting="safe")
TypeError: Cannot create a datetime string as units 'M' from a NumPy datetime with units 'D' according to the rule 'safe'

This throws an error because the "safe" rule does not allow to cast to a less specific unit.

unsafe

datetimes = [np.datetime64("2020-05-05"), np.datetime64("2020")]
np.datetime_as_string(datetimes, unit="M", casting="unsafe")
array(['2020-05', '2020-01'], dtype='<U25')

Here, no error this thrown since the "unsafe" rule allows for any form of casting.

robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Ask a question or leave a feedback...