Differences between revisions 3 and 9 (spanning 6 versions)
Revision 3 as of 2019-01-29 04:32:18
Size: 413
Editor: PieterSmit
Comment:
Revision 9 as of 2020-02-19 23:17:49
Size: 1248
Editor: PieterSmit
Comment:
Deletions are marked like this. Additions are marked like this.
Line 4: Line 4:
   * an f-string is created by prefixing the string with a f e.g. '''    * an f-string is created by prefixing the string with a f e.g. {{{
Line 6: Line 6:
     '''      }}}
Line 9: Line 9:
 * numbers '''
a= 10.1234
>>> f'{a:.2f}'
'10.12'
 * numbers f'{value:{width}.{precision}f}'  {{{
 a= 10.1234
>>> f'{a:.2f}'
 '10.12'
Line 16: Line 17:
'''
 * date '''
Line 19: Line 18:
''' >>> f'{75.765367:.0f}'
'76'
    }}}

 * date {{{
>>> f'test-{datetime.datetime.now():%Y-%m-%d_%H:%M:%S}.txt'
'test-2019-01-29_17:53:37.txt'

}}}
 * unix date time stamp ( seconds since 1970-01-01 ) {{{
f"{datetime.datetime.utcnow():%s}"
}}}

 * timestamp with timezone {{{
import datetime
tz = datetime.timezone.utc
ft = "%Y-%m-%dT%H:%M:%S%z"
t = datetime.datetime.now(tz=tz).strftime(ft)
print(f"== Summary {t} ==")

== Summary 2020-02-19T22:48:17+0000 ==
}}}

 * timestamp with specific timezone e.g. 'Pacific/Auckland' +12/+13 {{{
import datetime
import pytz # External timezone data, updates often

tz = pytz.timezone('Pacific/Auckland')
ft = "%Y-%m-%dT%H:%M:%S%z"
t = datetime.datetime.now(tz=tz).strftime(ft)
print(f"== Summary {t} ==")

== Summary 2020-02-20T12:04:14+1300 ==
}}}

Python Fstring formatting

  • f - string is the latest python string formatting addition, added in 3.5
    • an f-string is created by prefixing the string with a f e.g.

      f"this is a f-string"

Examples of f-strings

  • numbers f'{value:{width}.{precision}f}'

     a= 10.1234
     >>> f'{a:.2f}'
     '10.12'
    
    
    >>> f'{a*1000:,.2f}'
    '10,123.40'
    
    >>> f'{75.765367:.0f}'
    '76'
  • date

    >>> f'test-{datetime.datetime.now():%Y-%m-%d_%H:%M:%S}.txt'
    'test-2019-01-29_17:53:37.txt'
  • unix date time stamp ( seconds since 1970-01-01 )

    f"{datetime.datetime.utcnow():%s}"
  • timestamp with timezone

    import datetime
    tz = datetime.timezone.utc
    ft = "%Y-%m-%dT%H:%M:%S%z"
    t = datetime.datetime.now(tz=tz).strftime(ft)
    print(f"== Summary {t} ==")
    
    == Summary 2020-02-19T22:48:17+0000 ==
  • timestamp with specific timezone e.g. 'Pacific/Auckland' +12/+13

    import datetime
    import pytz  # External timezone data, updates often
    
    tz = pytz.timezone('Pacific/Auckland')
    ft = "%Y-%m-%dT%H:%M:%S%z"
    t = datetime.datetime.now(tz=tz).strftime(ft)
    print(f"== Summary {t} ==")
    
    == Summary 2020-02-20T12:04:14+1300 ==

Python/FStringsAndFormatting (last edited 2022-11-20 07:49:57 by PieterSmit)