python - How to replace missing parts of datetime strftime with zeroes? -


i receive date objects , need turn them string according format:

"%a %b %d %h:%m:%s %z %y" 

to achieve use python's datetime.strftime method. problem these date objects doesn't have data, example, can have both:

a = datetime.date(1999, 1, 2) b = datetime.datetime(2015, 10, 1, 9, 38, 50, 920000, tzinfo=datetime.timezone.utc) 

tried string format method:

"{:%a %b %d %h:%m:%s %z %y}".format(a) 

but if timezone not set dropped, so:

"{:%a %b %d %h:%m:%s %z %y}".format(b) 'thu oct 01 09:38:50 +0000 2015' 

but

"{:%a %b %d %h:%m:%s %z %y}".format(a) 'sat jan 02 00:00:00  1999' 

while expected be:

'sat jan 02 00:00:00 +0000 1999' 

is possible somehow fill timezone zeros?

as you've noticed strftime documentation, %z , %z yield empty string if datetime object naive, i.e. if doesn't have timezone set.

if want emit +0000 if don't know timezone, want treat utc.

so set default. if timezone isn't passed you, use timezone info did, i.e. tzinfo = datetime.timezone.utc. you'll +0000 in case.

update, in response comment:

realize, time you're @ lines beginning format, you're committed. datetime @ point naive or aware, , it's defined how strftime behave in either situation. when setting default, shouldn't @ format point, @ point of constructing datetime.

i can't give further specific without seeing more of code, have differentiates data have , b, must know if have tzinfo available. i'm going make example, can show put default:

for in magic_iterator:    (year, month, day, hour, minute, second, microsecond, timezone) = it.get_data()    # note, of these can none.  set defaults:    hour = hour or 0    minute = minute or 0    second = second or 0    timezone = timezone or datetime.tzinfo.utc     foo = datetime(year, month, day, hour, minute, second, microsecond, timezone)    # foo 

this construct or see if values falsey (i.e. false, 0, or empty string), , if so, set them appropriately. note in case of hour, minute , second, if actual value 0, or part of clause execute, since 0 falsey. logic error (solved doing hour = hour if hour not none else 0) in case, you'd setting 0 that's 0, it's ok.

come think of it, can 1 liner attached format, it's ugly:

"{:%a %b %d %h:%m:%s %z %y}".format(a if a.tzinfo else datetime(a.year, a.month, a.day, a.hour, a.minute, a.second, a.microsecond, datetime.tzinfo.utc)) 

i prefer put default in construction of datetime in formatting line.


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -