-1

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?

Harry Boy
  • 4,159
  • 17
  • 71
  • 122
  • 6
    Possible duplicate of [How to convert a date string to different format](https://stackoverflow.com/questions/14524322/how-to-convert-a-date-string-to-different-format) – Sayse Aug 22 '19 at 11:16
  • That "+00:00" is the time zone. If the input time zone is always zero, that's OK, but do you have to worry about different time zones? – Martin Bonner supports Monica Aug 22 '19 at 11:36
  • simply slice the string till milliseconds. str = str[:26] print(datetime.datetime.strptime(str, '%Y-%m-%d %H:%M:%S.%f').strftime('%Y-%m-%d %H:%M:%S.%f')) – Shafiqa Iqbal Aug 22 '19 at 11:38

2 Answers2

1

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
Amandeep Singh
  • 503
  • 3
  • 5
1

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.

Batman
  • 8,571
  • 7
  • 41
  • 80