0

I am trying to solve a problem:

In the library code I have something like:

return format % (value.year, value.month, value.day, value.hour, 
                 value.minute,value.second, value.microsecond)

where format is a string with formatting:

format = "%04d-%02d-%02d %02d:%02d:%02d.%06d"

For this format possible output can be:

2015-02-26 11:28:45.466000

I can only set up format (string format, maybe some function?), library code is untouchable. Is there any way to receive something like:

2015-02-26 11:28:45
4
  • string.split('.')[0] Commented Feb 26, 2015 at 11:34
  • What library? Why is it untouchable? Do you have more context to offer? Commented Feb 26, 2015 at 11:42
  • I'm pretty sure it's just datetime
    – PVNRT
    Commented Feb 26, 2015 at 12:30
  • Maybe I did not explain it enough.
    – Meaner
    Commented Feb 26, 2015 at 15:09

2 Answers 2

0

You have several amongst which:

  • Split the string and use it, which is great for a one-shot
  • Parsing the date back, which might be better if you are doing other operations on it

Here are these options with examples :


You can use the function split() to do this and use the character . as delimiter.
Note that this assumes that you will ever only get one point in your string.

result = "2015-02-26 11:28:45.466000" 
final_str = result.split('.')[0]
print(final_str)
>>> 2015-02-26 11:28:45

Parsing the date back with datetime :

import datetime

date_fmt = "%Y-%m-%d %H:%M:%S"
result_str = "2015-02-26 11:28:45.466000"

date = datetime.datetime.strptime(result_str, date_fmt+".%f")
date_str = date.strftime(date_fmt)

print(date_str)
>>> 2015-02-26 11:28:45
0

You can use the split() function

def reduce(mydate):
     newformat = mydate.split('.')[0]
     return newformat

print(reduce("2015-02-26 11:28:45.466000")) #2015-02-26 11:28:45

Documentation

1
  • It's "better" to have # for comments in python! :)
    – d6bels
    Commented Feb 26, 2015 at 11:52

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.