Skip to content

Unable to set modified date, created date and document id #330

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
HorusTheSonOfOsiris opened this issue Mar 10, 2021 · 2 comments
Closed
Labels

Comments

@HorusTheSonOfOsiris
Copy link

HorusTheSonOfOsiris commented Mar 10, 2021

When I try to update a file’s created date and modified date it doesn’t get updated. I can see that on SharePoint a new version is created but the field values doesn’t change.
@vgrem: please help
Here is the code:

file = ctx.web.get_file_by_server_relative_url('File path')
ctx.load(file)
ctx.execute_query()

fields = file.listItemAllFields.get().execute_query()
fields.set_property('Created', '2015-03-09T23:49:29Z', persist_changes=True)
fields.set_property('Modified', '2015-03-09T23:49:29Z', persist_changes=True)
fields.update()
ctx.execute_query()
@vgrem vgrem added the question label Mar 12, 2021
@vgrem
Copy link
Owner

vgrem commented Feb 20, 2022

Greetings,

rather late but anyway, it is nowadays (in version 2.3.11 or above) supported to update list item system metadata (namely Created/Modified/Author/Editor properties), here is an example:

ctx = ClientContext(site_url).with_credentials(credentials)

list_tasks = ctx.web.lists.get_by_title("Tasks")
items = list_tasks.items.get().top(1).execute_query()
if len(items) == 0:
    sys.exit("No items for update found")

item_to_update = items[0]  # type: ListItem
author = ctx.web.site_users.get_by_email(user_principal_name)

modified_date = datetime.utcnow() - timedelta(days=3)
result = item_to_update.validate_update_list_item({
    "Author": FieldUserValue.from_user(author),
    "Modified": modified_date
}).execute_query()

has_any_error = any([item.HasException for item in result.value])
if has_any_error:
    print("Item update completed with errors, for details refer 'ErrorMessage' property")
else:
    print("Item has been updated successfully")

@vgrem vgrem closed this as completed Feb 20, 2022
@r2oro
Copy link

r2oro commented Jul 20, 2023

Hello. My goal is to preserve modification time after value is assigned to a custom property of SharePoint file (unfortunately it changes modification time, what is not desired). I did follow example above. The query did not return exception. Actually I got positive response (if time format was wrong I was getting HasException == True), but it did not modification time correctly. Actually file modification time was updated to the time of when this request was sent!
This is the code I've written:

   def mark_processed(self, file):
        '''Set property of SharePoint file indicating that it was processed'''
        file_id = file.listItemAllFields.get().execute_query().id
        file_item = self.ctx.web.lists.get_by_title(self.sharepoint_lib).get_item_by_id(file_id).get().execute_query()
        file_metadata = file_item.properties
        mdate_utc = datetime.strptime(file_metadata['Modified'], SP_MDATE_READ_FORMAT).astimezone(tz=tz.utc)
        property_name = self.processed_poperty_name()
        if not property_name in file_metadata.keys():
            self.create_property(property_name)
        prop_value = datetime.today().strftime(SP_PROP_WRITE_FORMAT)
        file_item.set_property(property_name, prop_value).update().execute_query()
        logger.debug('Set %s property %s as %s', file.serverRelativeUrl , property_name, prop_value)
        # For some reason below does not work, despite the fact that people say it works for them...
        mdate_utc_str = mdate_utc.strftime(SP_MDATE_WRITE_FORMAT)
        client_result = file_item.validate_update_list_item(
            {'Modified': mdate_utc_str}
        ).execute_query()
        self.raise_for_o365(client_result)        
        logger.debug('Reversed modification time of %s to %s', file.serverRelativeUrl , mdate_utc_str)

    def raise_for_o365(self, result):
        '''Raise exception if o365 query request finished with exception'''
        for item in result.value:
            if item.HasException:
                raise requests.RequestException(f'SharePoint API resulted with error: {item.ErrorMessage}')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants