简体   繁体   中英

How to format a date string in python

I have a DateTime passed in from an external C# program to my python script in the following format:

2019-08-22 11:00:25.671640+00:00

But I have a python library that expects it in this format:

2019-08-21 17:04:36.501

How can I format the input string to this format always in python?

You can try following:

date = '2019-08-22 11:00:25.671640+00:00'
date_new = date.split('.')[0]

output

'2019-08-22 11:00:25'

if you need precision up to microseconds:

date_new=date.split('.')[0] + '.' + date.split('.')[1][:3]

output:

2019-08-22 11:00:25.671

The documentation covers this in depth.

Assuming that you've got an actual datetime object called dt , to get the format you want you'd do

 timestamp = "{:%Y-%m-%d %H:%M%S.%f}".format(dt)[:-3]

Python doesn't support millisecond resolution, so

timestamp = "{:%Y-%m-%d %H:%M%S.%f}".format(dt)

would give you 2019-08-21 17:04:36.501XXX . And then to take only the millisecond part you take the whole string, except the last three characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM