AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |
Back to Blog
Once you learn the format codes, you'll be good to go. You learned how to convert a string into a date format. Now we've gotten to the end of this tutorial. The small %m is used for months while the big %M is used for minutes. Make sure you don't confuse the format code %m with %M. If you do everything correctly and print it you should have something like this: Just follow the format for each part of the date and also pass in any respective symbols or letters you find in the date string.ĭo not get distracted by the symbols or letters in the string. We can see that there is nothing too complex about it. So all we need to do is create the proper format and the symbols in it. Now from the looks of it, we can see that this date string has year, month, day, hours, minutes and seconds. We will convert this string object to a date: "". Example – how to convert a string to a date Now that we understand that, let’s go over one more example that is more complex than the above. For example if we wish to get the year only, we can do that by typing date.year and it will print out just the year. We can decide to retrieve any attributes we want from it. When we print it after that, it will look like this. It requires two parameters: the date string and the format. The method datetime.strptime is the parser that will help us convert the date_string we passed into it as a date. If everything is done correctly, the format should be "%Y/% m/%d." Then we have another forward slash, and finally the day, for which the format code is %d.Īs a result, we must include the forward slash symbol in the format variable in the same way that it appears in the string. Then we have a forward slash followed the month, for which the format code is %m. The first element in the string represents a year, for which the format code is %Y. In this case, the string is in the format "9". We must be aware of the format ahead of time, that is before we pass it to the parser. The format variable declares the format of the date string to be passed to the parser (the function that will help us convert the date). Let's go over the above code again to make sure we understand what's going on. We can do that by typing the following: from datetime import datetimeįormat = %Y/%m/%d #specifify the format of the date_string.ĭate = datetime.strptime(date_string, format) We need to import the datetime library in Python to be able to achieve this. First, we'll convert the string "9" to the date. Let's look at some examples of string-to-date conversions. For example the %Y code requires 4 numbers to be passed as the year and its range is 0001 – 9999 (so 09, for example, wouldn't work – you need 2009). The element in the string must not exceed the range of the format code.
0 Comments
Read More
Leave a Reply. |