If we don’t want to use variables, we can hard code the date and/or the mask into the function call: datetime_object = datetime.strptime('', '%m/%d/%Y') If you don’t pass in a time value, then the value will always default to midnight. Datetime objects have a date and a time value. If we print the output of datetime_object, we will see that it shows: “ 00:00:00”Īll of the extra zeroes at the end are because we didn’t pass in a time. Next, let’s declare a variable and assign a string value to it: date1 = ""Īnd lets declare another variable containing our date mask: datemask = "%m/%d/%Y"įinally, let’s pass our date and mask into the strptime function: datetime_object = datetime.strptime(date1, datemask) We start by importing datetime: from datetime import datetime The strptime function takes two input variables: The main function you will use when converting a string is the strptime function. Converting from a stringīefore we can do anything else, we need to convert our string to a datetime object. A good resource for looking up additional maks variables can be found here. The above list is by no means comprehensive. Using the table above to construct our mask, we can describe our string of “” as “%m/%d/%Y” A few examples that we will use today are as follows: Description The datetime library has a special encoding you use to tell it which parts are which. Each part is separated by a forward slash. You can see that it starts with the month, followed by the day of the month, and ends with a 4 digit year. Let’s say you have a date you want to convert “”. It helps the system understand the input better. The mask references the format of the date you are trying to convert.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |